问题
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>
回答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") %>'
回答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
回答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
}
来源:https://stackoverflow.com/questions/5381139/linkbutton-send-value-to-code-behind-onclick