views:

36

answers:

2

Hello. I have a datagridview with 5000 entries. And I want to color the rows based on some values. Here's how I do it:

    foreach (DataGridViewRow row in rows)
    {
        var handlingStage = (ESourceHandlingStage)row.Cells["HandlingStage"].Value;
        switch (handlingStage)
        {
            case ESourceHandlingStage.NotStarted:
                row.DefaultCellStyle.BackColor = UnhandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Given:
                row.DefaultCellStyle.BackColor = GivenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Taken:
                row.DefaultCellStyle.BackColor = TakenColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Handled:
                row.DefaultCellStyle.BackColor = HandledColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            case ESourceHandlingStage.Loaded:
                row.DefaultCellStyle.BackColor = LoadedColor;
                row.DefaultCellStyle.SelectionBackColor = Color.Blue;
                break;
            default:
                break;
        }
    }

But when form loads it freezes for a couple of seconds. Can can I avoid it?
Thank you for your help!

+1  A: 

You're looping though all the rows so this will take some time, the more rows you have the more time it will take.

You could put this processing onto a background thread, but you will need to marshal the code so that the actual change occurs on the UI thread. This would take the same amount of time, but wouldn't lock the UI while it processed.

An alternative would be to change the colour as each row is added. However, that does depend on your data being added one row at a time.

ChrisF
+1  A: 

Try to color the row on databinding. I think you need to attach to the ItemDataBound event or something similar. Inspect the data and color the row accordingly. That way you don't have to loop over all the rows after they are created but instead you do your job when they are created.

AZ