Search code examples
c#asp.net.netlinkbutton

How to send a value from a LinkButton to the server?


I have many LinkButton such as:

<asp:LinkButton runat="server" onclick="cmdCancellaComunicazione_Click">X</asp:LinkButton> 

they call the same server method, cmdCancellaComunicazione_Click. but I need to distinguish them (passing to the server, for example, a value).

How can I do it? I know there is CommandArgument, but I can't set to it a value such as <%= myValue %>


Solution

  • Your code has no ID specified on your LinkButton which seems odd.

    You should be able to assign the CommandArgument server side with:

    yourLinkButton.CommandArgument = yourValue;
    

    And then it will be read it server side in your OnClick handler.

     protected void cmdCancellaComunicazione_Click(object sender, EventArgs e)
     {
         LinkButton btn = (LinkButton)sender;
         if (btn.CommandArgument.Equals(something here))
         {
              // do something
         }
         else
         {
              // do something else
         }
     }
    

    Is this being created in a grid or something that is being bound? If so I would implement the OnDataBinding event for the LinkButton like:

    <asp:LinkButton ID="yourLinkButton"
        runat="server" OnDataBinding="yourLinkButton_DataBinding"
        onclick="cmdCancellaComunicazione_Click">X</asp:LinkButton>
    

    Server side code (I try to avoid inline code whenever possible):

    protected void protected void lblID_DataBinding(object sender, System.EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        btn.CommandArgument = yourValue;
    }
    

    Is there something more to your scenario that you have not included in your question?