1

I have a button in ascx file, I want to call a method of my abc.aspx.cs file on clicking this button. Is there a way to do this from ascx.cs file? this is my button

<asp:ImageButton ID="ImageButton1" Style="padding-top: 80px; margin-right:10px;" runat="server"                            ImageUrl="~/App_Themes/Default/Images/Login/NH/DownloadButton.jpg" />
demo.b
  • 3,299
  • 2
  • 29
  • 29
Syed Salman Raza Zaidi
  • 2,172
  • 9
  • 42
  • 87

3 Answers3

1

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.

Markus
  • 20,838
  • 4
  • 31
  • 55
  • Another way to do this is to have the page set the event handler like here, https://stackoverflow.com/a/623355/6326441. – Bryan Euton Aug 07 '19 at 16:15
0

There is not such a facility in asp.net But you can use generic handler(.ashx) instead of this

King of kings
  • 695
  • 2
  • 6
  • 21
0

You can define a public method in aspx Page call it using this.Page

((YourASPXPage)(this.Page)).MyMethod();

In ASPX page

public void MyMethod()
{
     //Your code     
}
Adil
  • 146,340
  • 25
  • 209
  • 204