Creating Custom Colors in a DataGrid Cell
Listing 1. The DataGridTextBoxStyledColumn draws cells in a DataGrid using information from the data source. You write a class that implements ICustomGridCellProperties. This class will draw cells with a particular style. public class DataGridTextBoxStyledColumn : DataGridTextBoxColumn { private ICustomGridCellProperties _controller; public DataGridTextBoxStyledColumn( ICustomGridCellProperties controller ) { _controller = controller; } protected override void Paint( System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) { bool DisposeForeBrush = false; bool DisposeBackBrush = false; // the idea is to conditionally set the // foreBrush and/or backBrush // depending upon some criteria on the cell // value try { object src = source.List[ rowNum ]; if ( _controller != null ) { Color fg = _controller.GetForegroundColor( src ); foreBrush=new SolidBrush( fg ); DisposeForeBrush = true; Color bg = _controller.GetBackgroundColor( src ); backBrush = new SolidBrush( bg ); DisposeBackBrush = true; } } finally { // make sure the base class gets called to // do the drawing with the possibly changed // brush base.Paint( g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); if ( DisposeForeBrush ) foreBrush.Dispose(); if ( DisposeBackBrush ) backBrush.Dispose(); } } } |