在Asp.net Rowcommand事件中获取行索引

36

我有一个 ASP.NET GridView 控件:

<asp:TemplateField HeaderText="View Faktor" ShowHeader="False" Visible="True">
    <ItemTemplate>
        <asp:ImageButton ID="imgBtn1" CssClass="SelectRow" runat="server" CausesValidation="false"
            CommandArgument='<%#(eval("mprID")) %>' CommandName="ViewFactors" ImageUrl="~/tadarokat/Images/factor.png"
            Text="" />
    </ItemTemplate>
</asp:TemplateField>

在行命令事件发生时如何获取rowIndex

我想在RowCommand触发时突出显示(select)目标行。

6个回答

77
这是你问题的答案。
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

int RowIndex = gvr.RowIndex; 

14

ImageButton \ Button 等。

CommandArgument='<%# Container.DataItemIndex%>' 

代码后端

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

7
或者,您可以使用“控制”类而不是它们的类型:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

int RowIndex = row.RowIndex; 

4

如果你在GridView中使用了内置的命令,比如insert、update或delete,在行命令中,可以使用以下代码来获取索引:

int index = Convert.ToInt32(e.CommandArgument);

在自定义命令中,您可以将命令参数设置为yourRow.RowIndex.ToString(),然后在RowCommand事件处理程序中获取它。当然,除非您需要将命令参数用于其他目的。

2
我能够在我的项目中使用 @rahularyansharma 的答案,只需进行一点小修改。我需要获取用户单击 LinkButton 所在行的特定单元格的值。第二行可以修改为获取您想要的任意数量的单元格的值。
这是我的解决方案:
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

1
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {
        if (e.CommandName == "Delete")
        {
            GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
            int RemoveAt = gvr.RowIndex;
            DataTable dt = new DataTable();
            dt = (DataTable)ViewState["Products"];
            dt.Rows.RemoveAt(RemoveAt);
            dt.AcceptChanges();
            ViewState["Products"] = dt;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    try
    {
        gvProductsList.DataSource = ViewState["Products"];
        gvProductsList.DataBind();
    }
    catch (Exception ex)
    {

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接