views:

57

answers:

1

I am wondering what is the best way to go iterate through all the rows in a datagridview and get the values from the cells.
Here is what I am thinking of doing, but I don't really like it because if I rearrange the columns then the code will also have to be changed.

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];

        }
+2  A: 

You can use a foreach to iterate over the DataGridViewRows within the DataGridView and use the column names to retrieve the values from the 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();
}
CAbbott
Thank you, this is what I was looking for except I had to make a minor change from "dr.Cells["Col1"].ToString()" to "dr.Cells["Col1"].Value.ToString()"
David L
Glad it worked for you. I modified my answer to add `Value` for anyone else who finds this answer.
CAbbott
Ninja'd, I was about to add you need to have the Value to get the correct data from the Cell.
Justin