Wednesday, January 23, 2008

Changing the background color of cells in a DataGrid

How to change the background color of cells in a DataGrid depending on their value


For Code Mail Us :- codes.jinesh@gmail.com
Join Our Community :- Mad Engineerss..!






In this article I want to show how you can change the background color of a specific cells in a datagrid. .To do this you first have to create class derived from DataGridTextBoxColumn or DataGridColumnStyle. You then have to override the Paint() method of these classes. Note that this method has three overloaded versions.


In this method first you can check the value of cell in the column with the GetColumnValueAtRow method then set the brush you want, fill the cell rectangle then write the text with your proper font. Here is the sample code I used:


protected override void Paint(Graphics g, Rectangle Bounds, CurrencyManager Source,
int RowNum, Brush BackBrush, Brush ForeBrush,
bool AlignToRight)
{
bool bdel = (bool) GetColumnValueAtRow(Source, RowNum);
if(bdel == true)
BackBrush = Brushes.Coral;
else
BackBrush = Brushes.White;
g.FillRectangle(BackBrush, Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);
System.Drawing.Font font = new Font(System.Drawing.FontFamily.GenericSansSerif,
(float)8.25 );
g.DrawString( bdel.ToString(), font, Brushes.Black, Bounds.X, Bounds.Y);
}



Here I use column with a bool value and change the colors for true cells. Here you can change the font for them very easily too.


You can also change the overall style of the datagrid using the DataGridTableStyle and DataGridColumnStyle classes. The function below demonstrates this:


private void CreateDataGridStyle()
{
DataGridColumnStyle GridDelColumn;
DataGridColumnStyle GridSeqStyle;
DGStyle = new DataGridTableStyle(); //DGStyle is DataGridTableStyle
DGStyle.MappingName = "Table1";
GridSeqStyle = new DataGridTextBoxColumn();
GridSeqStyle.MappingName = "Column1";
GridSeqStyle.HeaderText = "Column1";
GridSeqStyle.Width = 100;
DGStyle.GridColumnStyles.Add(GridSeqStyle);
PropertyDescriptorCollection pcol = this.BindingContext[myDataSet,
"Table1"].GetItemProperties();
GridDelColumn = new ColumnStyle(pcol["Table1"]);
GridDelColumn.MappingName = "Column2";
GridDelColumn.HeaderText = "Column2";
GridDelColumn.Width = 100;
DGStyle.GridColumnStyles.Add(GridDelColumn);
DGStyle.AllowSorting = true;
DGStyle.RowHeadersVisible = true;
}



And after that you add the styles to datagrid:


CreateDataGridStyle();
myDataGrid.TableStyles.Add(DGStyle);
myDataGrid.SetDataBinding(myDataSet,"Table1");