Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update DatagridView Cell Background color based on row data

Hi I got a DatagridView and I would like it to change background color depending on the data in each row.

Ex.

| Person 1 | Person 2 | Person 3 |

|----100----|---200-----|-----150----|

|----300----|---100-----|------50----|

In the first row I would like it to make "100" have a red background color and "200" green. Or. The lowest value = red highest = green

Now the thing is that Im using a BindingList for my data, and its being updated async with INotifyPropertyChanged. So I need some way of checking each time one of the values has been updated.

Do the DataGridView have any event that would be usefull?

like image 693
gulbaek Avatar asked Aug 04 '10 12:08

gulbaek


2 Answers

Subclass DataGridView and override OnCellFormating(), in here you can inspect the cell value and set the colours appropriately.

In regard to comments below about using the corresponding event, yes you can do that but the virtual method has better performance and subclassing DataGridView encapsulates all the behavior of your grid in one place.

like image 177
Gary Avatar answered Oct 23 '22 23:10

Gary


Not too sure if this is the optimal solution but hope it helps: Register for the PropertyChanged event for each data source item in the datagrid view. In your event handler, you can perform the required action based on the changed values.
If you are using a binding list for your datasource, register for ListChanged to handle new items.

like image 28
Bharath K Avatar answered Oct 23 '22 23:10

Bharath K