As for the DataGridView, how do I get the values ​​from each row?

I am wondering what is the best way to iterate through all the rows in a datagridview and get the values ​​from the cells. Here's what I'm going to do, but I don't like it very much, because if I reorder the columns, then the code will need to be changed as well.

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]; } 
+7
c # winforms datagridview
source share
2 answers

You can use foreach to iterate over a DataGridViewRow in a DataGridView and use column names to retrieve values ​​from 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(); } 
+11
source share

A NullException may occur to avoid this error, you can modify the above code as follows

 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); } 
+1
source share

All Articles