How can i get the value of the next row of my DataGridView

965 views Asked by At

How can i get the value of the next row of my DataGridView in my FOREACH

foreach (DataGridViewRow row in dataGridViewSelection.Rows)
{
        if ((bool)((DataGridViewCheckBoxCell)row.Cells[3]).Value)
        {
            do
            {
                list.Add(row.Cells[1].Value.ToString());
            } 
            while (row.Cells[2].Value == the next row.Cells[2].Value-->of the next row);

        }              
}

I want to obtain the value of the same cell in the next row so i can compare them. Thank you

1

There are 1 answers

0
Reed Copsey On BEST ANSWER

You'll need to use a for loop instead of foreach, but this is simple since DataGridViewRowCollection implements the required info:

    for (int rowNum=0;rowNum<dataGridViewSelection.Rows.Count - 1; ++rowNum)
    {
            DataGridViewRow row = dataGridViewSelection.Rows[rowNum];
            if ((bool)((DataGridViewCheckBoxCell)row.Cells[3]).Value)                    {
                do
                {
                    list.Add(row.Cells[1].Value.ToString());
                } while (row.Cells[2].Value == dataGridViewSelection.Rows[rowNum+1].Cells[2].Value);

            }              
    }

By indexing via the index, you can easily access any other row in your loop.