ASP.NET VERSIONS: 1.0 | 1.1
Format Grid Columns at Run Time
Format DataGrid columns based on the cell value.
By Brad McCabe
In the last installment of this column (Expand the DataGrid), I showed you how to add tooltips to column headers. Continuing our look at the Microsoft DataGrid in this column, I'll try to address another frequently-asked question about the grid: Can you conditionally format columns of the grid at run time, based on the cell value?
Often times, having a similar format for all the cells in a column isn't the most desirable outcome. For example, you might wish to highlight negative values, or values below a specific range, with a red background.
The ability to do this is simpler than you might think. The DataGrid exposes an event - ItemDataBound - which is raised as each item is added to the grid. If you trap and handle this event, you can adjust the formatting of the cell at run time.
When the ItemDataBound event is fired, it passes a DataGridItemEventArgs parameter. Using this parameter, you can access the item property to gain access to the rows and cells that will be rendered as part of the grid.
The DataGridITemEventArgs parameter also exposes information about the DataRow that is used to create the row in the grid. This is exposed through the DataItem property.
The following code example handles the ItemDataBound event:
private void ItemDataBound (object sender,
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
DataRowView rv = (DataRowView)e.Item.DataItem;
Int32 SalesPrice = Convert.ToInt32(rv.Row.ItemArray);
if (SalesPrice < 10)
e.Item.Cells.BackColor = Color.Red;
If the sales price is below $10, it turns the cell background red. This example uses the value in the third column to obtain the sales price. This could easily be modified to be any column you needed in your example.
By handling the ItemDataBound event you are able to easily able to customize the look and feel of any cell based upon dynamic conditions evaluated at run time. Using this event you can customize the grid to highlight any cell you like.
Got a UI question, tip, or idea for a topic you'd like me to cover? I'd love to hear it. E-mail me at [email protected].
Brad McCabe is the technical evangelist for Infragistics. Brad also has been a systems architect and consultant for Verizon Communications and many other clients, and he was a leading .NET evangelist within Ajilon Consulting. His primary interests include ASP.NET, Windows CE .NET, .NET Compact Framework, and Microsoft's networking technologies. E-mail him at [email protected].