通过SelectedIndexChanged获取当前行
XHTML结构:
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" DataKeyNames="MATNR" CellSpacing="0" CellPadding="0" BorderWidth="0" GridLines="None" OnSelectedIndexChanged="gvList_SelectedIndexChanged" > <Columns> <asp:TemplateField HeaderText="操作"> <ItemTemplate> <asp:LinkButton runat="server" ID="lbtnShoppingCart" Text="+加入购物车" OnCommand="lbtn_Command" CommandName="Select" CommandArgument="ShoppingCart"> </asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
.cs(C#):
private string CmdArg = string.Empty; protected void lbtn_Command(object o, CommandEventArgs e) { CmdArg = e.CommandArgument.ToString(); } protected void gvList_SelectedIndexChanged(object o, EventArgs e) { GridView gv = (GridView)o; GridViewRow row = gv.Rows[gv.SelectedIndex]; switch (CmdArg) { case "ShoppingCart": string _Material = gvList.DataKeys[gvList.SelectedIndex].Value.ToString(); //code here ... }//end of if break; }//end of switch }