2016-03-02 97 views
0

我有一个从本地SQL服务器中提取数据一个gridview。我选择了3列在gridview上显示。我添加了第四列(选择命令)。我想摆脱这是一个ID的第一列中的数据,当我点击选择命令,但我总是得到一个错误“类型‘System.ArgumentOutOfRangeException’mscorlib.dll中发生的异常,但在用户代码的附加没有处理信息:索引超出范围,必须是非负数,小于集合的大小。“C# - Gridview帮助。 (ASP.NET)

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

有什么建议吗?

由于

+0

不'grdClients.Rows'返回任何记录? 'grdClients.Rows [grdClients.SelectedIndex] .Cells'如何?你需要确定它在哪一点失败,然后才能完全排除故障。虽然如果我不得不猜测,我不知道你是否正确地绑定了数据源。 – Marisa

+0

是的。我会尝试这个 –

回答

0

1-附加属性到GridView

DataKeyNames="aboutusID" 

2-一个TemplateField添加到列

<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 
     } 
    } 
} 
0

我认为你应该使用的SelectedIndexChanged事件为。
然后,你分配GridviewRow属性所选择的行“GridViewRow行= grdClients.SelectedRow;”

之后,你可以使用行获得第一个单元格的值,它曾经你想分配给您的会话或在哪里。 “row.Cells [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"); 
    } 
+0

谢谢你们, –

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"); 
      } 
}