Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Conditional Formatting ASP.NET DataGrid Columns

0.00/5 (No votes)
21 Apr 2003 1  
How to format ASP.NET datagrid columns by handling ItemDataBound event at run time.
Sample Image - GridColumnFormatting.gif

Like our previous article, How to remove DataGrid column, this article will try to answer another most frequently asked question about DataGrid controls, how can I conditionally format columns of a data grid control at run time? Believe it or not the answer to this question is very straight forward. When you call DataBind on a DataGrid control or for that matter whenever a grid gets bound to its datasource, ASP.Net framework fires ItemDataBound event. You can add an event handler for this event to take control of the rendering of DataGrid control.

The key to the solution is capturing ItemDataBound event. When the page recieves this event, complete information about the data row is available in DataGridItemEventArgs parameter of the event handler. Item property of this parameter contains information about the table rows and cells that will get rendered on the page. This parameter also contains the information about the DataItem that is being used to render information for the row. The data item corresponds to DataRowView object for that row's data. You can get the value for any given data field based on the field name or zero based index of data column.

For this article we have used the sample Northwind database and bound it to our DataGrid column.

private void OnNWDataBound(object sender, 
System.Web.UI.WebControls.DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { DataRowView rv = (DataRowView)e.Item.DataItem; // Get fourth column value. Int32 nUnitsInStock = Convert.ToInt32(rv.Row.ItemArray[4]); if (nUnitsInStock < 20) { e.Item.Cells[4].BackColor = Color.Red; } } }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here