asp.net - 如何从另一个用户控件继承用户控件?

标签 asp.net inheritance user-controls nullreferenceexception

是否可以从另一个用户控件继承用户控件?

我想要实现的是从另一个用户控件继承的用户控件。所以我有baseusercontrol.ascx,它只有文本“Stuff”。然后我有另一个用户控件 childusercontrol.ascx 从 baseusercontrol.ascx 继承。如果我不更改 childusercontrol.ascx 中的任何内容,我希望 baseusercontrol.ascx 文本显示“Stuff”。

而且我应该能够扩展派生的基本用户控制功能。

我也尝试过类似 this 的东西,但在我的情况下还不够。

现在我的 childusercontrol.ascx 看起来在下面

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="childusercontrol.ascx.cs" Inherits="test_childusercontrol" %>
<%@ Register src="baseusercontrol.ascx" tagname="baseusercontrol" tagprefix="uc1" %>

childusercontrol.ascx.cs 如下
public partial class test_childusercontrol : baseusercontrol
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }   
}

当我浏览此页面时,我收到错误消息
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.

有什么线索吗?

最佳答案

我已经为自己测试了这种情况。其实你不能继承来自 UserControl 的基类用它自己的 ASCX代码。

但是,您可以做的是 实现一些基本功能 在(可能是抽象的)基类(没有 ASCX )中,如下所示:

public class BaseClass:UserControl
{
    public String BaseGreeting { get { return "Welcomebase!"; }}
}

然后具体使用这个基类的方法和属性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; }
    }
}

关于asp.net - 如何从另一个用户控件继承用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19218640/

相关文章:

c# - 类型 'UserControl' 不支持直接内容

c# - 如何将应用程序转换为在中等信任级别下运行?

javascript - 使用 Resig 的简单 javascript 继承确定一个函数是否扩展另一个函数

c# - 覆盖某些 .Net Framework 控件的绘图以更改其边框颜色?

java - 是否可以让一个类(class)有多个超类(class)?

asp.net - Gridview PageIndexChanging 事件未触发

c# - 名称 'html' 也不存在于用户控件 MVC 和 C# 的当前上下文中的名称 'model'

c# - Gridview 标题卡住在母版页中不起作用

asp.net - 在整个网站上使用授权标签(排除)

c# - 通过服务器端 asp.net 代码将对象传递给 silverlight