41

I have a ASP LinkButton Control and I was wondering how to send a value to the code behind when it is clicked? Is that possible with this event?

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;"
    onclick="ENameLinkBtn_Click" ><%# Eval("EName") %></asp:LinkButton>
Yuck
  • 44,893
  • 13
  • 100
  • 132
atrljoe
  • 7,607
  • 11
  • 58
  • 109

3 Answers3

73

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'
Kelsey
  • 45,595
  • 16
  • 119
  • 161
  • 4
    You can declare the sender as LinkButton and skip the typecasting: protected void ENameLinkBtn_Click(LinkButton sender, EventArgs e) { string yourValue = sender.CommandArgument; // do what you need here } (Sorry, I tried but I CANNOT format the code) – Jovie Mar 10 '16 at 22:31
4

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

Ken Pespisa
  • 21,026
  • 3
  • 53
  • 61
1

Try and retrieve the text property of the link button in the code behind:

protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
   string val = ((LinkButton)sender).Text
}
dustyhoppe
  • 1,733
  • 16
  • 20