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>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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") %>'
Method 2
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
Method 3
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
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0