2011-08-17 81 views
0

我已經創建了datatable保存在會話&分配給gridview.I必須提取這些記錄,因爲我已經編寫代碼如下,但它的值爲null:如何從gridview中提取行gridview c#

//To find gridview in Formview1 
    GridView GridView1 = (GridView)Formview1.FindControl("GridView1"); 
    GridView1.DataSource = (DataTable)Session["tabdetails"]; 
    GridView1.DataBind(); 

    string str, str1, str2, str3, str4, str5, str6; 
    for (int i = 0; i < GridView1.Rows.Count; i++) 
    { 
     str = GridView1.Rows[i].Cells[0].Text; 
     str1 = GridView1.Rows[i].Cells[1].Text; 
     str3 = GridView1.Rows[i].Cells[2].Text; 
     str4 = GridView1.Rows[i].Cells[3].Text; 
     str5 = GridView1.Rows[i].Cells[4].Text; 
    } 

請建議我做正確的更改? 謝謝。 Asp.net c#

+0

如果你不打算編輯UI中的內容,直接從'Session [「tabdetails」];'。這會容易得多。 –

+0

如果要更改UI中的內容,那麼對於每一行,在單元格內找到相應的文本框控件並從中獲取值。 –

回答

1

使用數據鍵來存儲您需要檢索的值。

<asp:GridView ID="GridView1" runat="server" DataKeyNames="SomeColumnName, AnotherColumnName, SomeOtherColumnName" ... > 

而且在後面的代碼:

for (int i = 0; i < GridView1.Rows.Count; i++) 
{ 
    GridViewRow row = GridView1.Rows[i]; 
    string str = GridView1.DataKeys[row.RowIndex]["SomeColumnName"]; 
} 
+0

感謝它的工作 – abc

2

您可以使用每個循環

foreach (GridViewRow GR in GridView1.Rows) 
{ 
    if (GR.RowType == DataControlRowType.DataRow) 
     {      
      string myField = GR.Cells[1].Text; 

      // You can also find grid view inside controls here 

      TextBox tb = (TextBox)tt.FindControl("TextBox1"); 
     } 
} 
0

如果你在你的GridView細胞控制提取網格視圖行,該文本值會空着。如果你有一個簡單的文本框,你應該修改你的代碼來使用「Controls」集合。

str = ((TextBox)GridView1.Rows(i).Cells(0).Controls(1)).Text; 

使用索引[1]而不是[0],因爲通常索引[0]將是文字控件。