In order to do this in a clean way without coupling the page and the user control, you can create an event in the user control that the parent aspx form subscribes to.
For details on events in C#, see this link.
UserControl.ascx.cs
public class MyUserControl : UserContro
{
public event EventHandler ImageButtonClicked;
private void ImageButton1_Click(object sender, EventArgs e)
{
if (ImageButtonClicked != null) // Check against null as there may not be any subscribers
ImageButtonClicked(this, EventArgs.Empty);
}
// ...
}
WebForm.aspx
<!-- ... -->
<uc:MyUserControl ID="myUserCtrl" runat="server" ImageButtonClicked="myUserCtrl_ImageButtonClicked" />
<!-- ... -->
WebForm.aspx.cs
// ...
private void myUserCtrl_ImageButtonClicked(object sender, EventArgs e)
{
// Call method on page.
}
// ...
Please note that there an be no or many subscribers to the event. If you want to transmit data to the event handler, you need to create your own EventArgs implementation and use an instance of these instead of EventArgs.Empty
. This also allows you to check whether the event has been handled by a subscriber, you can add a Handled
boolean property to your EventArgs that is set by an event handler and evaluated in the user control afterwards.