LinkButton Send Value to Code Behind OnClick
Solution 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") %>'
Solution 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
Solution 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
}
Related videos on Youtube
atrljoe
I am Senior Level Developer who enjoys learning new things and helping people. I am especially interested in c# but have worked with many languages.
Updated on February 13, 2020Comments
-
atrljoe over 4 years
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>
-
Jovie about 8 yearsYou 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)