How do I color a individual cell depending upon its value or some external method
We give three different methods for doing this.
The first one overrides Paint in a derived columnstyle and sets the backcolor there.
The second uses a delegate to set the color in the Paint override.
The third method adds an event to the derived column style to allow you to set the color in an event handler.
You can do this by deriving from DataGridTextBoxColumn and overriding the Paint method to conditionally set the backColor and foreColor. The sample code below colors any cell that starts with a letter higher than ’F’.
You can download a project (C#
) using this class.
To use some method to provide the cell color, you can use a similar technique as discussed above. But instead of setting the color based on cell value, call a delegate method instead. This delegate can be passed in using the constructor for the custom column style. You can download a sample
that shows how this can be done.
If you want a more flexible solution, you could expose an event as part of your derived columnstyle that fires in the Paint override. This would allow the handler of the event to set the color value depending upon the row and column parameters that are passed as part of the event args. You can download a sample (C#
) that implements this technique. The sample actually handles allowing a cell to be editable on a cell by cell basis through an event. This sample colors the back ground of the disabled cell gray. You could modify the eventargs to include a backcolor, and use this event to color cells based on row and column values removing the event call in the Edit override.