0
votes

I want to color certain rows in my dataGridview and do so succesfully with the below code, however once I add more rows to my datagridview, they all reset to white.

This code checks all the rows from a previous collection that made it in the datagridview and colors them lightblue. These rows are matched by sets, and the background color indicates what rows are together and every set it alternates between white and blue.

Adding another set of rows to the datagridview resets the background color to white for all previous rows in the datagridview and I have no clue why, should I overload a certain event? I'm at a loss.

This is the only instance of me changing the color of anything and I have no events of any kind overwritten.

List<DataRow> dgvr = new List<DataRow>();

foreach(DataGridViewRow row in dataTaken1.SelectedRows)
{
    // Adding selected rows from the first datagridview to the set
}

foreach (DataGridViewRow row in dataTaken2.SelectedRows)
{
    // Adding selected rows from the second datagridview to the set
}

foreach(DataRow row in dgvr)
{
    dataTable1.Rows.Add(row); // This is the dataTable that is bound to the datagridview
    dataTable1.AcceptChanges();
    dataGridView1.Update();
}

if (bordercolor % 2 == 1)
{
    foreach (DataRow row in dgvr)
    {
        dataGridView1.Rows[dataTable1.Rows.IndexOf(row)].DefaultCellStyle.BackColor = Color.LightBlue;
    }
}

bordercolor++; // ensures that the next set has a different background color

EDIT: Here is a picture showing how i want my rows to show, alternating colors between sets, for example, grey being odd numbered sets color and light blue being even numbered sets color.

enter image description here

1

1 Answers

2
votes

You may want to check this property instead of doing it manually: