Windows Develop Bookmark and Share   
 index > Windows Forms General > How to color a particular cell in datagrid based on some condition.
 

How to color a particular cell in datagrid based on some condition.

I have a datagrid control which consist of three columns first consisit of boolean second text and thirdconsist of integer data types. Now i want if my boolean column consist of true value its corresponding integer column should consist of value greater than zero. If this is not the case then its backcolor should change to red. This color change should happen before my user wants to save the data into the databse.Please help me out how can i do this. I am a newbie in this field.

Any kind of help would be appreciated.

Thanks a lot in advance.....

Deeps_123  Friday, December 22, 2006 11:07 AM

You can do this in multiple ways. It depends a bit on the exact needs and when the cell needs to change color.

Here is a solution that changes the color of the cell when it is loaded. If needed, it is also possible to change the color of the cell when other cell changes. Herefor you need to hook on a different event.

On the RowPrePaint event, add the following code:

private void dgSampleGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
   if (!e.IsLastVisibleRow)
   {
      DataGridViewRow row = dgSampleGrid.Rows[e.RowIndex];
      if ((bool)row.Cells["boolColumn"].Value && (int)row.Cells["intColumn"].Value < 0)
      {
         row.Cells["intColumn"].Style.BackColor = Color.Red;
      }
   }
}

The e.IsLastVisibleRow check is done to avoid changing colors on the Edit row. It is possible to set this row off.

Greetz,

Geert

 

Geert Verhoeven
Consultant @ Ausy Belgium

My Personal Blog

Geert Verhoeven  Friday, December 22, 2006 11:46 AM

You can use google to search for other answers

Custom Search

More Threads

• what cause the blank desktop after logon to windows 2000 pro?
• e.Cancel = true (disable application close alt-f4 & application.exit();) how to override?
• A Class Populating a form
• How to prevent a Win Form from show up the second time
• How to programatically change system color settings
• Duplicating the contents of a treeView
• DropDownList, Autocomplete, Tab gives unexpected behavior
• The Form events are not caught
• Trouble with points and windows
• How to use controls in an executable?