Sud*_*dha 5 asp.net inheritance user-controls nullreferenceexception
是否可以从另一个用户控件继承用户控件?
我想要实现的是从另一个用户控件继承的用户控件.所以我有baseusercontrol.ascx,这只是文本"Stuff".然后我有另一个用户控件,childusercontrol.ascx从baseusercontrol.ascx继承.如果我没有在childusercontrol.ascx中更改任何内容,我希望baseusercontrol.ascx文本显示"Stuff".
而且我应该能够扩展派生的基本用户控制功能.
我也试着像这样,但它在我的情况还不够.
现在我的childusercontrol.ascx看起来在下面
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="childusercontrol.ascx.cs" Inherits="test_childusercontrol" %>
<%@ Register src="baseusercontrol.ascx" tagname="baseusercontrol" tagprefix="uc1" %>
Run Code Online (Sandbox Code Playgroud)
childusercontrol.ascx.cs如下
public partial class test_childusercontrol : baseusercontrol
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Run Code Online (Sandbox Code Playgroud)
当我浏览此页面时,我得到错误
Object reference not set to an instance of an object.
Description : An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details : System.NullReferenceException: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
任何线索?
我已经为自己测试了这种情况。实际上,您不能从具有UserControl自己ASCX代码的基类继承。
但是,您可以做的是在(可能是抽象的)基类(没有)中实现一些基本功能,ASCX如下所示:
public class BaseClass:UserControl
{
public String BaseGreeting { get { return "Welcomebase!"; }}
}
Run Code Online (Sandbox Code Playgroud)
然后在UserControl拥有自己ASCX文件的具体类中使用这个基类的方法和属性。
public partial class childusercontrol : BaseClass
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Greeting = base.BaseGreeting; //As initial value
}
public String Greeting
{
get { return LabelGreeting.Text; }
set { LabelGreeting.Text = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7339 次 |
| 最近记录: |