0

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

基本上,我想从第一列获取 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");
}

有什么建议么?

谢谢

4

3 回答 3

0

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
        }
    }
}
于 2016-03-02T22:16:05.583 回答
0

我认为您应该为此使用 SelectedIndexChanged 事件。
然后将 GridviewRow 属性分配给选定的行“GridViewRow row = grdClients.SelectedRow;”

之后,您可以使用 row 获取第一个单元格的值并将其分配给您的会话或您想要的任何地方。“行。单元格[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");
    }
于 2016-03-03T04:15:42.103 回答
0

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

以下是我的解决方案:

 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");
            }
}
于 2016-03-03T16:19:17.580 回答