Search code examples
c#.netsharepointsharepoint-2013web-parts

How can I retrieve the ID of the clicked button from the method handling this event into a SharePoint 2013 Web Part?


I am pretty new in .NET and SharePoint (I am working on SharePoint 2013) and I have the following problem developing a Web Part.

Into my Web Part I have this ImageButton:

ImageButton btnApplica = new ImageButton();
btnApplica.ToolTip = "Documento in Entrata";
btnApplica.Click += btnApplica_Click_Scelta_Campi_Etichetta;
btnApplica.ID = "btnEntrata";
btnApplica.ImageUrl = "/_layouts/15/images/MyProject/Default/Ribbon/DocEntrataRibbon.png";

As you can see this clicking on this button is performed the btnApplica_Click_Scelta_Campi_Etichetta() method, this one:

void btnApplica_Click_Scelta_Campi_Etichetta(object sender, EventArgs e)
{
    Debug.Print("btnApplica_Click_Scelta_Campi_Etichetta START");

    SPWeb contextWeb = SPContext.Current.Web;
    string url = contextWeb.Url;

    string link = url + "/ARXEIA WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj=" + obj;

    SPUtility.Redirect(link, SPRedirectFlags.Default, Context);

}

It works fine. My problem is: from the inside of this btnApplica_Click_Scelta_Campi_Etichetta(object sender, EventArgs e) method can I retrieve the clicked button? The ID (iin this case the btnEntrata value) should be perfect.

I want to use this method to handle the click on different buttons instead create a new method for each button.

Can I do something like this? How can I retrieve the ID of the clicked button?


Solution

  • You can parse the sender variable to a button and then get the ID for example:

    void btnApplica_Click_Scelta_Campi_Etichetta(object sender, EventArgs e)
    {
        Debug.Print("btnApplica_Click_Scelta_Campi_Etichetta START");
        ImageButton btnApplica = (ImageButton) sender;
        String idBtn = btnApplica.ID;
    
        SPWeb contextWeb = SPContext.Current.Web;
        string url = contextWeb.Url;
    
        string link = url + "/ARXEIA WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj=" + obj;
    
        SPUtility.Redirect(link, SPRedirectFlags.Default, Context);
    
    }