I\'ve a user control registered in an aspx
page
On click event of a button in the user control, how do i call a method which is there in the parent page\'s code
Follow good and appropriate approach,
Use event and delegate concept make delegate as same signature as your method in parent page and then assign parent methad to it in parent page load event then call this delegate through event in user control.
code sample and link is given below.
//Parent Page aspx.cs part
public partial class getproductdetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ucPrompt.checkIfExist += new uc_prompt.customHandler(MyParentMethod);
}
bool MyParentMethod(object sender)
{
//Do Work
}
}
//User control parts
public partial class uc_prompt : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public delegate bool customHandler(object sender);
public event customHandler checkIfExist;
protected void btnYes_Click(object sender, EventArgs e)
{
checkIfExist(sender);
}
}
Read more details how it works (Reference) :-
Calling a method of parent page from user control
I want to do this scenario:
LoadEditCategory
method (parent method).LoadEditCategory
) needs a int
argument (CategoryID
).RightControlPanel
that is in same parent page folder.Child User control
1- Add a Action
(_LoadEditCategory
)
public Action<int> _LoadEditCategory = null;
<int>
is int
argument (CategoryID
).
2- Use this Action
in button event (btnSave
button name) like this:
void btnSave_Click(object sender, EventArgs e)
{
//123 is test integer for CategoryID
_LoadEditCategory(123);
}
Parent Page or parent user control
3- Add parent method
private void LoadEditCategory(int CategoryID)
{
// CategoryID is 123 in my example
//Do some things with CategoryID
}
4- Add this code when load child user control (RightControlPanel
)
//Load child user control
RightControlPanel si = this.LoadControl(this.ControlPath + "RightControlPanel.ascx") as RightControlPanel;
if (si != null)
{
...
//For call parent method in child user control
si._LoadEditCategory = c => LoadEditCategory(c);
...
}
Cast the page as the specific page in your project:
((MyPageName)this.Page).CustomMethod()
//c#
//In parent page
public void test(string S)
{
Label1.Text = S;
}
//In user control
protected void Button1_Click(object sender, System.EventArgs e)
{
//Calling "test method" of parent page from user control
((object)this.Page).test("Hello!!");
}
'VB.Net
'In parent page
Sub test(ByVal S As String)
Label1.Text = S
End Sub
'In user control
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'Calling "test method" of parent page from user control
DirectCast(Me.Page, Object).test("Hello!!")
End Sub