2016-03-02 96 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"); 
      } 
}