Search code examples
c#datagridviewbackcolor

C# Datagridview change row color based on condition only first 1000 records


i have a little problem with my datagridview. I am filling the Datagridview with my records from the db.

But i want to change the back- and forecolor in a specific condition. It works fine but only with the first 1000 records and the problem is i have more than 10.000 records. Did i have a wrong event?

I'd be grateful for a better solution.

Best regards

my code:

private void dataView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach(DataGridViewRow row in dataView.Rows)
    {
        int value = Convert.ToInt32(row.Cells[2].Value);

        if(value == 1)
        {
            row.DefaultCellStyle.BackColor = Color.Orange;
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.White;
        }
    }
}

Solution

  • The CellFormatting event is not the best option in your case. Your for loop is causing you to iterate over your data multiple times.

    You can use the RowPrePaint, RowPostPaint or the DataBindingComplete events for your scenario.

    Using the RowPrePaint will allow you to color the row and leave open the option to apply additional cell level styling for individual cells.

     private void dataView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
     {
         DataGridViewRow row = dataView.Rows[e.RowIndex];
         if (Convert.ToInt32(row.Cells[2].Value) == 1)
         {
             row.DefaultCellStyle.BackColor = Color.Orange;
         }
         else
         {
             row.DefaultCellStyle.BackColor = Color.White;
         }
     }
    

    If you choose to keep your loop then you can use the DataBindingComplete event.

    private void dataView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row in dataView.Rows)
        {
            int value = Convert.ToInt32(row.Cells[2].Value);
            if (value == 1)
            {
                row.DefaultCellStyle.BackColor = Color.Orange;
            }
            else
            {
                row.DefaultCellStyle.BackColor = Color.White;
            }
        }
    }