The DataGrid provides a plethora of properties that can be set to specify the DataGrid's formatting. For example, you can have each consecutive row of a DataGrid alternate between two different colors merely by setting the DataGrid's AlternatingItemStyle's BackColor property.
While the AlternatingItemStyle is a great way to apply different formatting for every other DataGrid row, oftentimes developers want to perform conditional formatting based on the value(s) of a DataGrid row. For example, imagine a DataGrid that displays a list of products, including the product's name and price. Perhaps you want to draw the user's attention to products that are at "bargain-basement" prices. Namely, if a product has a price less than, say, $10.00, you want to have that row highlighted.
This can be accomplished by providing an event handler for the DataGrid's ItemDataBound event. The
ItemDataBound fires once for each DataGridItem added to the DataGrid (that is, it fires once
for each row that is added to the DataGrid). Essentially, what we need to do is in this event handler, check to see if
the price is below the threshold ($10.00, or whatever lower bound you choose). If it is, then we want to set the
DataGridItem's BackColor property to Yellow, thereby highlighting the row.
This can be accomplished with the following code:
|
|
| VB.NET |
|
|
| C# |
Checking the e.Item.ItemType Property |
Note that in both the VB.NET and C# code examples, the first thing we did in the event handler was
check to ensure that the DataGridItem's ItemType was either an Item or
AlternatingItem. This is because the ItemDataBound event fires for all created
rows in the DataGrid, including the Header and Footer rows. However, we only want to check to see if
we should apply highlighting to those rows that are being bound to the DataGrid's DataSource
(namely the Item and AlternatingItem rows)... hence the reason for this conditional.
|
All that remains is to wire up the DataGrid's ItemDataBound event to the
ItemDataBoundEventHandler event handler. This can be accomplished by simply adding
OnItemDataBound="ItemDataBoundEventHandler" to the DataGrid's declaration, like so:
|
|
| <shameless plug> |
| Chapter 11, "Altering the Data Before It's Rendered," talks more in depth about conditional formatting, as well as how to handle conditional formatting for database fields that can contain NULL values! |
| </shameless plug> |
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.