gridview获取当前行索引的方法大集合

<ItemTemplate>
                                <center>
                                <asp:ImageButton ID="linkBtnUpdate" runat="server" CommandName="Update" CommandArgument='<%# Eval("ValueID") %>'  ImageUrl="~/images/修改.png" OnClick="linkBtnUpdate_Click" />
                                </center>
                            </ItemTemplate>

方法一:在GridView中的RowCommand事件中获取

if (e.CommandName.Equals("Update"))
        {
            //取id的值方法一   
            //GridViewRow drv = ((GridViewRow)(((ImageButton)(e.CommandSource)).Parent.Parent)); //此得出的值是表示那行被选中的索引值
            //string id = gvFieldValue.DataKeys[drv.RowIndex].Value.ToString(); //此获得的值为gridview中绑定数据库中的主键值

            //取id的值方法二   
            GridViewRow drv = ((GridViewRow)(((ImageButton)(e.CommandSource)).Parent.Parent)); //此得出的值是表示那行被选中的索引值
            
            //此获得的值为gridview中绑定数据库中的主键值,取值方法是选中的行中的第一列的值,drv.rowindex取得是选中行的索引
            Label lblKey = gvFieldValue.Rows[drv.RowIndex].FindControl("lblKey") as Label;
            string a = lblKey.Text;

           //取id的值方法三  
            //因为在客户端中就已经将linkbutton的commandargument与主键id给绑定了所以在此可以直接用e.commandargument得出主键id的值
            int id = Convert.ToInt32(e.CommandArgument.ToString()); 
}

方法二:ImageButton的Click事件中获取

protected void linkBtnUpdate_Click(object sender, EventArgs e)
    {

        ImageButton btnUpdate = (ImageButton)sender;//强转以下
        ValueId = btnUpdate.CommandArgument.ToString();

         int row = ((GridViewRow)((ImageButton)sender).NamingContainer).RowIndex;
        // GridView1.Rows[drv.RowIndex].Cells[0].Text;
        Label lblkey = (Label)gvFieldValue.Rows[row].FindControl("lblKey") as Label;
        string a = lblkey.Text;

    }

原文地址:https://www.cnblogs.com/wuhuisheng/p/2001808.html