Click here to Skip to main content
6,595,444 members and growing! (19,919 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

Practical use of the DataGrid's ItemDataBound event.

By Luc Archambault

Using the ItemDataBound event to modify the content and formatting of any cell in a DataGrid.
C#, Windows, .NET 1.0, ASP.NET, Visual Studio, Dev
Posted:27 Oct 2004
Views:144,061
Bookmarked:37 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
28 votes for this article.
Popularity: 5.74 Rating: 3.97 out of 5
2 votes, 7.1%
1
2 votes, 7.1%
2
3 votes, 10.7%
3
9 votes, 32.1%
4
12 votes, 42.9%
5

Sample Image

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

// First we add our handler (OnItemDataBound) to the datagrid's ItemDataBound event

this.myDataGrid.ItemDataBound += new 
  System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
// This is our handler for the datagrid's ItemDataBound event.

private void OnItemDataBound(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    // Check if the current row contains items; if it's

    // a header or footer row that will throw an error

    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // Get a copy of the "dgLabel2" label that contains the 

        // "Balance" value

        Label lblBalance = (Label)e.Item.FindControl("dgLabel2");
        // Convert the value contained in the label to a double type

        double dblBalance = Convert.ToDouble(lblBalance.Text);
        // If that numeric value is negative

        if(dblBalance < 0)
            // ...display it in red

            e.Item.Cells[3].ForeColor = System.Drawing.Color.Red;
        // Get a copy of the "dgLabel1" label that contains the 

        // "Country" value

        Label lblCountry = (Label)e.Item.FindControl("dgLabel1");
        // ...convert it to a string

        string strCountry = lblCountry.Text;
        // If it's a North American country...

        if(strCountry == "USA" || 
            strCountry == "Mexico" || 
            strCountry == "Canada")
        {
            // Get a copy of the "dgLabel0" label that contains the 

            // "CustomerID" value, we'll use it in the query string 

            // for the popup

            Label lblID = (Label)e.Item.FindControl("dgLabel0");
            // ...convert it to a string

            string strID = lblID.Text;
            // Replace the "Country" value displayed in the datagrid

            // with "Jamaica", placed in a hyperlink who's OnClick 

            // event calls a javascript "popup" window

            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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Luc Archambault


Member
I have been working with different web technologies (ASP, ASP.NET, ColdFusion, Perl/CGI) for the past 7 years. I live in Montreal, where I work for a little consultant group specializing in Microsoft technologies.
Occupation: Web Developer
Location: Canada Canada

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
GeneralExcellent PinmemberNaumanLeghari1:17 29 Dec '06  
GeneralSimple Solution Pinmembermuffingal10:51 20 Jun '06  
GeneralYou don't need labels [modified] PinmemberHarteex6:02 8 Jun '06  
GeneralThank you Pinmembergungk9:27 31 Mar '06  
GeneralKidding me? Pinmembereanderson12:52 3 Nov '04  
GeneralRe: Kidding me? PinsussAnonymous12:47 21 Dec '04  
GeneralRe: Kidding me? PinsussAnonymous9:22 3 Feb '05  
GeneralRe: Kidding me? Pinmemberrobdeyric7:39 14 Aug '09  
GeneralRe: Kidding me? PinmemberTechnicaOne15:15 3 Feb '05  
GeneralRe: Kidding me? PinsussAnonymous16:23 8 Jun '05  
GeneralRe: Kidding me? Pinmembershakoosh10:51 18 Jul '05  
GeneralRe: Kidding me? PinmemberChristian Islas7:54 27 Jul '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Oct 2004
Editor: Smitha Vijayan
Copyright 2004 by Luc Archambault
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project