So, it’s time to tackle the next question in the original list of Scott Hanselman’s ASP.NET interview questions.  This time, the question asks to describe what events are fired when binding data to a data grid and what they could be used for.  If you are looking for a very technical overview, MSDN has the scoop on all of the data grid binding events.  Since this is a blog (and therefore not meant to be a technical document), I’ll try to approach the topic with a bit more of a pragmatic eye and give some example code usages.

On the the events!

The easiest way to figure out what events you have at your disposal is to create a DataGrid on your .aspx page and browse through the different intellisense options that pop-up beginning with "On".

Intellisense


As you can see in the image above, DataGrids in ASP.NET can do much more than display data.  However, in this case, we are only interested in the events that get fired as part of the process that binds the data to the DataGrid.  It turns out, out of the myriad of events that can be utilized, only two of them happen as part of the data binding process.  These two events are the ItemCreated event and the ItemDataBound event.

 

ItemCreated:

The ItemCreated event is fired when an item in a DataGrid control is created.  This means that at the time the event is fired, the DataGrid does not yet know about the data that will be bound to it.  So, if the logic of your method depends on this data being available to the control, you’re better off using the ItemDataBound event.  Other than that, the ItemCreate event differentiates itself in one other way from the ItemDataBound event: the ItemCreated event is raised when data is bound to the control and during round-trips (postbacks).  These qualities make the event especially well-suited to add custom attributes to a DataRow (such as onmouseover or other javascript events) or to control the appearance in ways that do not depend on the data within the DataRow (such as making every 10th row a different color).

 

ItemDataBound:

The ItemDataBound event is fired after after an item in a DataGrid control is bound.  This means that (unlike the ItemCreated event) you can add special formatting to a DataRow that is dependent upon the data contained within that row.  Since ItemDataBound is fired after the ItemCreated event, it is within this event that you are presented with the final opportunity to access the data before it is rendered to the client.  These qualities make the event well-suited for changing the appearance of a row or cell based on the data within that row or cell (such as highlighting outliers or other important information).

 

Example:

Assume we have the following DataGrid declared on our .aspx page:

<asp:DataGrid ID="MainDataGrid"
    runat
="server"
    AutoGenerateColumns
="true"
    OnItemDataBound
="MainDataGrid_ItemDataBound"
    OnItemCreated
="MainDataGrid_ItemCreated" />

On the code behind page then, we can create the following two methods to handle adding titles to header row, to specify more descriptive headers, and to change the row background color based on an employee’s salary:

protected void MainDataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
   
//If the item is in the header
    if (e.Item.ItemType == ListItemType.Header)
   
{
       
//Iterate through each cell
        foreach(TableCell item in e.Item.Cells)
       
{
           
//Add the title attribute — we could just as easily
            //add a javascript onmouseover event here
            item.Attributes.Add("title", item.Text);
       
} </p>

        </font>//Since the header values are set before we have access
        //to the data, we can modify the third column header to
        //be a bit more descriptive
        e.Item.Cells[2].Text = "Salary (in US$)";
   
}
} </div>

 
protected void MainDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
   
//Since DataGrid differentiates between Items and AlternatingItems, you sometimes have to check
    //for one *or* the other
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   
{
       
//Here we will modify the row color based on the salary
        //We can only do this within ItemDataBound since it relies
        //on the data being available from the data source
        if (Convert.ToInt32(e.Item.Cells[2].Text) < 10000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightPink;
       
}
       
else if (Convert.ToInt32(e.Item.Cells[2].Text) < 1000000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightBlue;
       
}
       
else
       
{
           
e.Item.BackColor = System.Drawing.Color.LightGreen;
       
}
   
}
}

 

I created a sample DataTable that I have bound to.  Using the two methods above, I get the following output in the browser:

 SampleOutput 


If it helps, I have include a sample project that you can use to get started with your project.  You can download it here.

Hopefully that gives you a good idea of how best to take advantage of the events fired as part of binding data to a DataGrid.  If you have any questions or comments, please feel free to add them to the comment section.  I find these blog entries to be a great learning experience for me, so I’d love to know if they’ve been helpful to anyone else.