I have a repeater that has a LinkButton in one of its columns and I have the onclick event wired up. When the user clicks on one of the options, I need to know in the event which LinkB开发者_如何学Goutton they clicked on. What is the best practice to do this?
You should use the OnCommand
event instead of OnClick
use some CommandName
and CommandArgument
to distinguish b/w items. This MSDN page has an example.
Normally CommandArgument='<%#Eval("Id")
is used for such purpose
<asp:LinkButton ID="LinkButton1" runat="server"
CommandArgument='<%#Eval("Id") %>' CommandName="commandName"></asp:LinkButton>
and then it will be like...
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName == "commandName")
{
Int32 id = Convert.ToInt32(e.CommandArgument);
}
}
What you want to do is wire up the Repeater's ItemCommand
event and not use the LinkButton's OnClick
event. Instead wire up the CommandName
of the LinkButton.
When the ItemCommand fires you'll be able to tell what button triggered it based on the CommandName
that was set on the button. You'll also have access to all the controls in that row of the Repeater.
MSDN http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemcommand.aspx
Check with this code
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
repTriggers.DataSource = new int[3] { 0, 1, 2 };
repTriggers.DataBind();
}
}
protected void repTriggers_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "trigger")
{
LinkButton btn = e.CommandSource as LinkButton;
if (btn != null)
{
lblUpdate.Text = "Update triggered by " + btn.ID + e.Item.ItemIndex.ToString();
}
// [Steve] removed UpdatePanel2.Update()
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager>
<%-- [Steve] removed UpdatePanel1 --%>
<asp:Repeater ID="repTriggers" runat="server" OnItemCommand="repTriggers_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkTrigger" runat="server" Text="Trigger" CommandName="trigger"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="conditional">
<%-- [Steve] added repTriggers as an AsyncPostBackTrigger --%>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="repTriggers" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblUpdate" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Source URL http://forums.asp.net/p/1062060/1528071.aspx
精彩评论