Search code examples
c#asp.netonclicklinkbutton

Get which Link button has been clicked


I am working on an ASP.NET/C# Application.

I have Link buttons like this

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="Link_Click">Link1</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="Link_Click">Link2<Chart</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" OnClick="Link_Click">Link3</asp:LinkButton>

Is there a way to know which one was clicked in the Link_Click event?

I don't want to create a different event for each link.

I am looking for something like this:

protected void Link_Click(object sender, EventArgs e)
{
    string LinkClicked = Get_Which_Link_Has_Been_Clicked();

    if(LinkClicked == "Link1")
    {
        //DoSomething;
    }
    else if(LinkClicked == "Link2")
    {
        //Do something else;
    }
    //and so on;
}

Thanks in advance.


Solution

  • Try casting the sender value passed to the function to a LinkButton then getting the id from that -

    LinkButton lbtn = (LinkButton)sender;
    string id = lbtn.ID;