Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Calling a method in parent page from user control?

I have a a gridview in my usercontrol .. on its rowcommand of one button ... i want to call method in parent page's codebehind?


((MyPageName)this.Page).CustomMethod();

I used this way to do that ... but wehn i google that .. i came to know that there is problem is with type of way /// can u suggest me any alternative ?/
Posted
Updated 25-Sep-13 23:42pm
v2

My solution for this would be to expose the event in the user control and attach a method from parent.
 
Share this answer
 
Comments
Torakami 26-Sep-13 5:48am    
Can you suggest me the code ..
Torakami 26-Sep-13 5:48am    
Because I want to do that on gridviews row command
ArunRajendra 26-Sep-13 6:50am    
Try this. This sample is taken from stackoverlow site.

public partial class Main
{
public void function1()
{
doing_stuff_here();
}

private void button1_Click(object sender, EventArgs e)
{
var update = new UpdateDialog();
update.OnButton2Click += OnUpdateDialogButton2Click;

update.ShowDialog();
}

void OnUpdateDialogButton2Click(object sender, EventArgs e)
{
function1();
}
}

public partial class UpdateDialog
{
public event EventHandler<eventargs> OnButton2Click;

private void button2_Click(object sender, EventArgs e)
{
//call here function1() from Main

if (OnButton2Click != null)
{
this.OnButton2Click(this, e);
}
}
}
This thing will be done with the help of event handling that i have done i the folowing code.
GridView gv = (GridView)UserControl.FindControl("gridview1");
       gv.RowCommand += new GridViewCommandEventHandler("name of the event you want to call from parent page");
 
Share this answer
 
You could try
C#
this.NamingContainer
instead of
C#
this.Page
and I would do it like this:

C#
MyPageName objMyPageName = this.NamingContainer as MyPageName;

C#
if(objMyPageName != null)
{
   objMyPageName.CustomMethod();
}
 
Share this answer
 
Comments
Torakami 26-Sep-13 7:40am    
Its not working ..
obgmypagename is taking null only ..
Azee 26-Sep-13 7:52am    
Could you leave the code and actual name of the Page in which you have the User Control. I produced the scenario and its working for me. In my scenario if MyPageName is name of your page and the User Control is placed inside this page then it should work.

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