I have a Default.aspx page and I am using a usercontrol in it. On some condition in usercontrol.cs I have to invoke a function present in Default.aspx.cs page (i.e parent page of user control). Please help and tell me the way to do this task.
-
[This Will help you](http://stackoverflow.com/questions/623136/calling-a-method-in-parent-page-from-user-control?rq=1) – Damith Apr 03 '13 at 11:39
4 Answers
You have to cast the Page
property to the actual type:
var def = this.Page as _Default;
if(def != null)
{
def.FunctionName();
}
the method must be public:
public partial class _Default : System.Web.UI.Page
{
public void FunctionName()
{
}
}
But note that this is not best-practise since you are hard-linking the UserControl
with a Page
. Normally one purpose of a UserControl is reusability. Not anymore here. The best way to communicate from a UserControl
with it's page is using a custom event which can be handled by the page.
Mastering Page-UserControl Communication - event driven communication

- 450,073
- 74
- 686
- 939
Add an event to the user control:
public event EventHandler SpecialCondition;
Raise this event inside your user control when the condition is met:
private void RaiseSpecialCondition()
{
if (SpecialCondition != null) // If nobody subscribed to the event, it will be null.
SpecialCondition(this, EventArgs.Empty);
}
Then in your page containing the user control, listen for the event:
public partial class _Default : System.Web.UI.Page
{
public void Page_OnLoad(object sender, EventArgs e)
{
this.UserControl1.OnSpecialCondition += HandleSpecialCondition;
}
public void HandleSpecialCondition(object sender, EventArgs e)
{
// Your handler here.
}
}
You can change the EventArgs
to something more useful to pass values around, if required.

- 5,341
- 1
- 25
- 43
parent.aspx.cs
public void DisplayMsg(string message)
{
if (message == "" || message == null) message = "Default Message";
Response.Write(message);
}
To Call function of parent Page from user control use the following: UserControl.ascx.cs
this.Page.GetType().InvokeMember("DisplayMsg", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { "My Message" });
This works fine for me..

- 1
Try this
MyAspxClassName aspxobj= new MyUserControlClassName();
aspxobj.YourMethod(param);

- 1,677
- 13
- 24
-
1Are you kidding? Apart from the fact that a `UserControl` is not a `Page`, using a constructor to create a page(or `UserControl`) will not work if you want to access controls on that `Page` or `UserControl` since this instance is not created from ASP.NET through a page's lifecycle. – Tim Schmelter Apr 03 '13 at 11:58