C# - 网格视图帮助.(ASP.NET)



我有一个从本地SQL服务器中提取数据的网格视图。我选择了 3 列显示在网格视图上。我添加了第四列(选择命令)。当我单击 select 命令时,我想从第一列中获取数据,这是一个 id,但我总是收到错误"mscorlib 中发生了类型为'System.ArgumentOutOfRangeException'的异常.dll但没有在用户代码中处理 其他信息:索引超出范围。必须是非负数且小于集合的大小。

基本上,我想从第一列获取id,然后将其分配给会话变量,然后重定向到第二页,然后使用该会话变量的内容填充另一个文本框。

    protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
      string id = grdClients.Rows[grdClients.SelectedIndex].Cells[0].Text.ToString();
      Session["ID"] = id;
      Response.Redirect("secondPage.aspx");
}

有什么建议吗?

谢谢

1- 将属性添加到 GridView

DataKeyNames="aboutusID"

2-将模板字段添加到列中

<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" CommandName="SelectSession" Text="EDIT"  CommandArgument='<%# DataBinder.Eval(Container,"RowIndex")%>' ></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

3-在你的代码中

protected void GridViewAbout_RowCommand(object sender, GridViewCommandEventArgs e)
{
    // this to skip on paging or sorting command
    if (e.CommandName != "Sort" & e.CommandName != "Page")
    {
        // Get the command argument where the index of the clicked button is stored
        int index = Convert.ToInt32(e.CommandArgument);
        // Get the data key of the index where the id is stored
        int id = Convert.ToInt32(GridViewAbout.DataKeys[index].Value);
        if (e.CommandName == "SelectSession")
        {
            // Your Code
        }
    }
}

我认为你应该使用SelectedIndexChanged事件.
然后,将 GridviewRow 属性分配给所选行"GridViewRow row = grdClients.SelectedRow;"

之后,您可以使用行获取第一个单元格的值,并将其分配给会话或所需的任何位置。"行。细胞[0]。文本;"

    protected void grdClients_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = grdClients.SelectedRow;
        string id = row.Cells[0].Text;
        Session["ID"] = id;
        Response.Redirect("secondPage.aspx");
    }

谢谢大家,我能够通过从您提供的每个解决方案中取出碎片来提出解决方案。非常感谢。

以下是我的解决方案:

 protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
 {
            if (e.CommandName == "Select")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string id = grdClients.Rows[index].Cells[0].Text.ToString();
                Session["ID"] = id;
                Response.Redirect("secondForm.aspx");
            }
}

最新更新