Reputation: 1657
I have a button in my usercontrol. When that button is clicked I need to call a method that is in aspx page.
How do I do that?
Thanks
Upvotes: 1
Views: 698
Reputation: 12495
Don't know VB.Net that well, but in C# on the code behind I would add:
/// <summary>
/// Relay
/// </summary>
public event EventHandler ButtonClick;
protected void BtnClick(object sender, EventArgs e)
{
if (this.ButtonClick != null) this.ButtonClick(sender, e);
}
I think the VB.Net would be (but really not sure!):
Public Event ButtonClick as EventHandler
Private Sub BtnClick(ByRef sender as object, ByRef e as EventArgs)
RaiseEvent ButtonClick(sender, e)
End Sub
This exposes an event on the UserControl which can be used in the Page to wire up to it.
On the mark up for the Asp:Button in the UserControl, set the OnClick="BtnClick"
and it should relay the event to the event on the UserControl.
In the mark up for the page add OnButtonClick="PageBtnClick"
to the UserControl mark up, which can then call the method of the page you wish.
Upvotes: 0
Reputation: 67068
FYI I am a C# guy you will need to convert my solution to vb.net, or if someone wishes to edit this answer that would be swell. I could try and remeber the syntax but then I'd get it wrong and add more confusion then its worth.
This works, all were doing is casting the Page to the right type:
((MyParentPageType)this.Page).Method()
With that said I wouldn't recommend doing this. You've essentially hardwired this user control to the parent page. You could at a minimum define an Interface that any page that contains this control must implement. At this point you have provided a little bit of decoupling.
An even better mechanism would be for the user control to raise an event, that the parent page will subscriber to. This is how all the other controls work. You can do this like
In your UserControl add an Event:
private static readonly object EventClick=new object();
public event EventHandler<ClickEventArgs> Click
{
add
{
base.Events.AddHandler(EventClick, value);
}
remove
{
base.Events.RemoveHandler(EventClick, value);
}
}
Then your page will add a handler for the Click event, then you can fire the event when you need. Now you have decoupled your user control from the page.
Upvotes: 1