Gernony
Gernony

Reputation: 75

Changing style of certain cells in DataGridView

I'm trying to change the color of certain cells in a DataGridView depending on wether the value is the same as in other cells. Sadly though, it's not working. This is the code which I thought should work:

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    for (int j = 1; j < 8; j++)
        for (int k = 8; k < 20; k++)
            if (dataGridView2.Rows[i].Cells[j].Value == dataGridView2.Rows[i].Cells[k].Value)
                dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Green;
}
dataGridView2.Refresh();

All columns are created with typeof(int) so it shouldn't be a type problem. Also debugging showed my program does enter the if-clause, yet still it doesn't display the changes.

Thanks in advance for any help.

Upvotes: 1

Views: 5081

Answers (1)

Brandon
Brandon

Reputation: 1279

I am doing this in one of the apps I work on. Near as I can figure, the best way to do it is to override the DataGridView.CellFormatting event.

In my app, there are four boolean properties on each row of the datasource, I want to add a colored box for each of the properties that is true.

    void uxGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        try
        {
             var item = uxGrid.Rows[e.RowIndex].DataBoundItem as NiftyThing;
             if(item != null)
             {
                 if(item.Property1)
                 {
                     e.CellStyle.SelectedBackColor = e.CellStyle.BackColor = Color.Red;
                     //Don't display 'True' or 'False'
                     e.Value = string.Empty;
                 }
                 else if(item.Property2)
                 ...
             }      
        }
        catch { }
    }

I hope that helps!

Upvotes: 1

Related Questions