How to inherit a UserControl from another UserControl?

拥有回忆 提交于 2019-12-07 06:49:32

问题


Is it possible to inherit a User control from another user control?

The thing I'm trying to achieve is a user control inheriting from another user control. So I have baseusercontrol.ascx, and this just has text "Stuff". Then I have another user control, childusercontrol.ascx inheriting off of baseusercontrol.ascx. If I don't change anything in childusercontrol.ascx, I would expect the baseusercontrol.ascx text to display of "Stuff".

And also I should be able to extend the base user control functionalities in derived one.

I have also tried something like this, but its not enough in my case.

Now my childusercontrol.ascx looks lie below

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

childusercontrol.ascx.cs as below

public partial class test_childusercontrol : baseusercontrol
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }   
}

When I browse this page Im getting error as

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.

Any clue?


回答1:


I have tested this situation for myself. Actually you can not inherit from a base class that is a UserControl with it's own ASCX code.

What you can do however, is implementing some basic functionality in a (possibly abstract) base class (without ASCX) like this:

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

And then use the methods and properties of this base class in concrete UserControl classes that have their own ASCX file.

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; }
    }
}


来源:https://stackoverflow.com/questions/19218640/how-to-inherit-a-usercontrol-from-another-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!