GridView中模版列使用RowCommand事件如何得到当前列的行索引或记录ID

转载出自:http://www.cnblogs.com/netsutang/archive/2007/05/01/734050.aspx

可以使用SelectButton:
<asp:CommandField ShowSelectButton="True" />
这样在RowCommand中获得的e.CommandArgument就是当前行的索引

如果是使用模板列,可以把数据的任意一列绑定到按钮的CommandArgument,如下:

<asp:TemplateField>

<ItemTemplate>

<asp:Button runat="server" CommandArgument='<%# Eval("id") %>' Text="Button" />

</ItemTemplate>

</asp:TemplateField>

一般可以绑定到主键列,这样可以在RowCommand通过e.CommandArgument获取当前行的主键,也便于进行其他操作

如果是要获取行索引,比较麻烦一点,还是那个Button1,在GridView的RowDataBound事件中如下:

Button btn = (Button)e.Row.FindControl("Button1");

if (btn != null)

{

btn.CommandArgument = e.Row.RowIndex.ToString();

}

这样就可以在RowCommand中通过e.CommandArgument获取行索引了

不过感觉用行索引的时候比较少,一般都是通过主键的

原文地址:https://www.cnblogs.com/fantaohaoyou/p/777380.html