2010-04-05 53 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); 
}