2010-04-05 58 views
7

我想知道什麼是最好的方式去遍歷datagridview中的所有行,並從單元格中獲取值。
這是我正在考慮的,但我不太喜歡它,因爲如果我重新排列列,那麼代碼也將不得不改變。對於DataGridView,我如何從每一行獲取值?

for (int i = 0; i < dataGridView.RowCount; i++) 
{ 
    string Value0 = dataGridView1.Rows[i].Cells[0]; 
    string Value1 = dataGridView1.Rows[i].Cells[1]; 
    string Value2 = dataGridView1.Rows[i].Cells[2]; 
} 

回答

11

您可以DataGridView內使用foreach遍歷DataGridViewRow S和使用列名從檢索值Cells:可能出現

foreach (DataGridViewRow dr in dataGridView.Rows) 
{ 
    string col1 = dr.Cells["Col1"].Value.ToString(); 
    string col2 = dr.Cells["Col2"].Value.ToString(); 
    string col3 = dr.Cells["Col3"].Value.ToString(); 
} 
+1

謝謝,這是我正在尋找的,除了我不得不做一個從「dr.Cells [」Col1「]。ToString()」改爲「dr.Cells [」Col1「]。Value.ToString()」 – skid 2010-04-05 21:44:53

+0

很有幫助。我修改了我的答案,爲找到這個答案的其他人添加「Value」。 – CAbbott 2010-04-05 21:49:18

+0

Ninja'd,我即將添加您需要有值才能從Cell中獲取正確的數據。 – Justin 2010-04-05 21:53:40

1

NullException避免這種錯誤,您可以修改上面的代碼如下

foreach (DataGridViewRow dr in dataGridView1.Rows) 
{ 
    //variables with looop through 
    string col1 = Convert.ToString(dr.Cells["col1"].Value); 
    string col2 = Convert.ToString(dr.Cells["col2"].Value); 
    string col3 = Convert.ToString(dr.Cells["col3"].Value); 
}