Introduction
This article is for the beginner level audience who has just started working on user controls. Sometimes while using user controls, you may need to access methods declared either on the parent user control and parent page from the child user control. Here is a simple solution for that.
Background
I came across the same issue where I needed to access the method declared on the parent user control from the child user control and ended up searching for options. I got a simple solution using abstract
classes as it was not possible to access the user defined methods in the Parent
object.
Here is the little trick. I have created abstract class AbstractUserControl
and AbstractPage
, where AbstractUserControl
is inherited from System.web.UI.UserControl
and AbstractPage
is inherited from System.Web.UI.Page
. I placed these two classes inside the App_code folder so that it will be accessible anywhere in the site.
Using the Code
Here is the abstract
class with the declaration of abstract
methods. These abstract
methods will be overridden in the Page
or UserControl
where they need to be called from the child.
namespace CodeProject.Sample
{
public abstract class AbstractPage : System.Web.UI.Page
{
public AbstractPage()
{
}
public abstract void callMefromChild();
}
}
I added a similar abstract
class for a user control to inherit.
Next, I use these abstract
classes to achieve the functionality. Now it is pretty straight forward to access the parent page method from the child control. Here is the snippet:
protected void btnClick_Onclick(Object sender, EventArgs e)
{
((AbstractPage)Parent.Page).callMefromChild();
}
Simple type casting of Parent.Page
to the AbstractPage
classes exposes the user defined method in the Page
. We can use the same trick for accessing the method declared on the parent user control from the child user control.
I am a long time user of The Code Project and never contributed to the community. Today I am starting with this simple article and expecting to come up with some interesting stuff later on. Hope this helps somebody. Please free to post a comment if you need any clarifications.