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