This step-by-step article describes how to use the ItemDataBound event of the Web Forms DataGrid, DataList, and Repeater controls to perform special processing on individual rows of data that are displayed in a data-bound list control.
When you display a list of items in a data-bound list control, you may want to apply conditional logic to display different information, or to apply different formatting, to different items. You can use the ItemDataBound event to apply this logic because each individual row of data is processed and displayed.
Switch to the "code behind" module (WebForm1.aspx.cs) by right-clicking WebForm1.aspx in Solution Explorer, and then clicking View Code.
Add the following statements at the top of the code module:
using System.Data.SqlClient;using System.Data.Common;
Add code in the Page_Load event to retrieve the list of customers from the sample Northwind database to a SqlDataReader object, and then bind the Repeater control to the DataReader. Modify the connection string as necessary in the code that follows to connect to an available SQL Server:
SqlConnection cn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;User ID=user;Password=password"); cn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", cn); SqlDataReader dr = cmd.ExecuteReader(); Repeater1.DataSource = dr; Repeater1.DataBind();
Run the project. A bulleted list of contact names from the Northwind Customers list is displayed on the page. Each contact name is formatted in blue by default.
If the data source is a DataReader object, you must cast e.Item.DataItem as type DBDataRecord (from System.Data.Common) in the event handler. If the data source is a DataTable object, you must cast e.Item.DataItem as type DataRowView.
Even if you have not created an <AlternatingItemTemplate> in your Repeater control, every other row still has an ItemType of ListItemType.AlternatingItem. Therefore, you must check for both ListItemType.Item and ListItemType.AlternatingItem to process every row.