WWW Yariv Hammer's Code Site

Thursday, October 20, 2005

How to set the ForeColor of the text in a cell based on a condition.

In my previous post I showed how to use DataGridColumnStyles to customize the look of the DataGrid. I will show how to further customize the DataGrid.
Sometimes you need your DataGrid to behave in a very special way. For example: To put an image instead of text, or set some cells as Readonly. In order to acheive these kinds of behavior you will need to inherit from DataGridColumnStyle or one of its derived classes.
I will not show in this article every aspect of this method, but a small example.

In the previous post I showed a Transaction table, with a Balance column. Lets say we want this column to show negative values in red, and positive numbers in black.

We will derive from DataGridTextBoxColumn as follows:

public class PaintedColumnStyle:DataGridTextBoxColumn
   protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
      foreBrush = new SolidBrush(GetColor(GetColumnValueAtRow(source,rowNum)));
      base.Paint (g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);

   private Color GetColor(object text)
      if (text == DBNull.Value)
         return Color.Black;
      int num;
         if (text.GetType() == typeof(int) )
            num = (int) text;
            num = int.Parse((string)text);
         return Color.Black;
      if (num<0)
         return Color.Red;
      return Color.Black;

I override the Paint method and change the ForeBrush as needed. I guess you would have imagined a use of ForeColor property of some sort. Well, no such property and we need the help of the System.Drawing namespace (Brush class).

The method GetColumnValueAtRow is used to get the value in a specified row in the DataSource in the current column. It is implemented for us in the base class.
I coded GetColor in order to find out whether to draw the text in red or black.

Now, instead of using DataGridTextBoxColumn as in the previous example, we use the PaintedColumnStyle we have just created:

(...) //see previous post
PaintedColumnStyle balanceColumn = new PaintedColumnStyle();
// balanceColumn - no change here
balanceColumn.HeaderText = "Balance";
balanceColumn.MappingName = "Balance";
balanceColumn.ReadOnly = true;
balanceColumn.Width = 75;


In the next article I will show how to calculate the Balance column based on the rows above it in the DataGrid.


Post a Comment

<< Home

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.