Introduction
Because of its simplicity, flexibility and many possible uses, the DataGrid
class is one of the most well known and used classes of the .NET framework. The use of the DataGrid
's ItemDataBound
event introduces a whole new world of possibilities, letting you conditionally modify displayed data, format, as well as insert some client side code for any cell in your DataGrid
. The use of this event can sometimes be a smart alternative to adding calculated columns to a dataset.
The source code available for this tutorial is a working example of what you can do with the ItemDataBound
event; a DataGrid
displays customer information, a balance value is displayed in red if its value is negative. For the sake of this tutorial, we'll pretend that Jamaica has invaded the North American continent, so North American countries are displayed as "Jamaica" with the insertion of client side code to create a hyperlink and map this link's onClick
event to a JavaScript function (popup window). The source code contains an Access database and two web forms; the DataGrid
and a form letting the user view complete details of the customer in the popup window.
Background
The ItemDataBound
event happens once for every row, after the data is bound to the DataGrid
and before the page is rendered to the client.
Using the code
this.myDataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
private void OnItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblBalance = (Label)e.Item.FindControl("dgLabel2");
double dblBalance = Convert.ToDouble(lblBalance.Text);
if(dblBalance < 0)
e.Item.Cells[3].ForeColor = System.Drawing.Color.Red;
Label lblCountry = (Label)e.Item.FindControl("dgLabel1");
string strCountry = lblCountry.Text;
if(strCountry == "USA" ||
strCountry == "Mexico" ||
strCountry == "Canada")
{
Label lblID = (Label)e.Item.FindControl("dgLabel0");
string strID = lblID.Text;
e.Item.Cells[2].Text = "<a href=\"popup.aspx?id=" + strID +
"\" onClick=\"popup(this.href); return false;\">Jamaica</a>";
}
}
}
Points of Interest
The ItemCreated
event is a close sibling of ItemDataBound
. This event happens before ItemDataBound
, when the row is created but does not yet contain any data, so you can't use it to read or modify data.