Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
i have made a BaseUserControl.ascx and a ChildUserControl.ascx
file. both have its own code behind file.
So what i want,
i wanted to inharit ChildUserControl.ascx file
to BaseUserControl.ascx. so whatever in my BaseUserControl.ascx file
should be visible into the ChildUserControl.ascx,
means if i have kept a TextBox in BaseUserControl.ascx should be visible
into the ChildUserControl.ascx desing view. and it should be accessible into the ChildUserControl.ascx code behind file.

1) Is this possible, if yes then how?

2) if above is possible then How to access BaseUserControl.ascx code behind file into the ChildUserControl.ascx code behind file?
Posted

1 solution

1. This is of course possible.

Suppose, following is the BaseUserControl.ascx

XML
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BaseUserControl.ascx.cs" Inherits="BaseUserControl" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


You need to register this user control in another user control (ChildUserControl) and use that as follows:

XML
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ChildUserControl.ascx.cs" Inherits="ChildUserControl" %>
<%@ Register src="BaseUserControl.ascx" tagname="BaseUserControl" tagprefix="uc1" %>
<uc1:BaseUserControl ID="BaseUserControl1" runat="server" /

>

And, if you register the ChildUserControl.ascx in an aspx page, you will see the TextBox from the BaseUserControl.ascx will be shown

2. Yes, it might be possible to inherit the code behind of a user control by anothe user control, but, it is suggested to put the base user control codes inside a base class (That inherits the System.Web.UI.UserControl) and then inherit the class by the code behind classes of the user controls. That is:

//Put this inside the App_Code
class UserControlBase : System.Web.UI.UserControl
{
}

class ChildUserControl : UserControlBase
{
}
 
Share this answer
 
Comments
Leon Zeng 3-May-15 23:56pm    
This is embedding not inheritance. If you place ChildUserControl (id=ChildUserControl1) in a page, you will see TextBox1 in ChildUserControl1, but it's null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900