Post navigation

Using the ItemDataBound Event

An ItemDataBound event is raised each time an item (row) is data bound to a DataGrid. Once this event is raised,an argument of type DataGridItemEventArgs is passed to the event handling method and the data relevant to this event is available.This data is is no longer available once your application exits the event handling method. The eventhandler for ItemDataBound isOnItemDataBound.We can specify the method that should handle the event which takes the event source object(in our case the datagrid) and the DataGridItemEventArgs as arguments.

This can be explained easily with the help of an example. Consider the case where you want to calculate the total of a column in a datagrid.

First, let us create a data table and add rows to it with the following C# code:

Since we are using ItemDataBound event to to total up the price column in the data grid, we have tospecify on the web form (.aspx) page, the method that would handle the ItemDataBound event (Event wiring).This is acheived by mentioning within the datagrid control tag that on the occurence of the event

How does this code work? The itemDataBound method is called as each row(item) is bound to the datagrid.
Within the method, we check if the current row is a header or a footer row.To do this we use ListItemType enumeration.
For now, all we need to know is that ListItemType enumeration contains different types of items(header, footer,item, alternating item etc. ) that can be included in a list control (in our case, a datagrid). Therefore, if we want to check if the it bound a datagrid footer,a simple if statement like this would do the trick:

if(e.Item.ItemType == ListItemType.Footer) { // your code }

In our method, we add the value in the price column to the total if the datagrid item is not a header or footer. Finally, when thedatagrid footer is encountered, we display our total on the footer row of the datagrid.This is possible becauseItemDataBound eventis the last oppurtunity to access the data item before it is displayed in the browser.