Developer

Understanding the ASP.NET DataGrid control

Trying to present tabular data in ASP often resulted in numerous HTML <table> elements fighting for attention with inline ASP function calls and statements. Fortunately, ASP.NET provides the DataGrid control, making it easy to populate a grid with data.


Tabular presentation of data: Love it or hate it, as a programmer, you just can't live without it. In the past, overzealous ASP programmers and the "spaghetti" style of coding resulted in the use of numerous HTML <table> elements fighting for attention with inline ASP function calls and statements. This was a nightmare to maintain, which is why ASP.NET provides the very cool and useful DataGrid server control. This control makes it easy to populate a "grid" (table) with "data" (rows and columns). Valid sources of data can range from static arrays to records retrieved dynamically from a database. Interested? Read on.

Basics of the DataGrid
Let's start with a simple example of a DataGrid populated with my favorite superheroes:
<script Language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {   
 
       string [] arysuperheroes = {"Super Man", "Bat Man", "Green Lantern",
"Spider Man"};      
      
       // set the source of the datagrid
       dgsuperheroes.DataSource = arysuperheroes;
 
       // bind the data to the grid
       dgsuperheroes.DataBind();
}
</script>
<html>
<body>
<asp:datagrid id="dgsuperheroes" runat="server" />
</body>
</html>

Save this as "heroes.aspx" under your Web server root, and view it in your browser to obtain the following result. This code works by first defining a string array, titled arysuperheroes, to store a list of values. The next step is to assign the array to the DataGrid via its DataSource property. Finally, by invoking the DataBind() method of the DataGrid object, I "bind" the data from the source to the grid in order to render it on the screen.

Dynamic heroes
Of course, a static array is just the tip of the iceberg. This next example demonstrates how you can populate a DataGrid from an MS-SQL database:
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<script Language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {   
 
       // invoke the custom "BindMe" function
       // to bind the datagrid with the data
       BindMe();
}
 
// function to bind the records retrieved
// from the database to the "dgsuperheroes" datagrid
void BindMe() {
 
       // build the connection string
       string strConn = "user id=sa;password=sa;";
       strConn += "initial catalog=pubs;data source=mydbserver;";
      
       // connect to the database
       SqlConnection objConn = new SqlConnection(strConn);
      
       // query
       string strSQL = "SELECT * FROM superheroes";
 
       // create an instance of the DataReader object
       SqlCommand objCommand = new SqlCommand(strSQL, objConn);
       objConn.Open();
       SqlDataReader objReader = objCommand.ExecuteReader();
      
       // assign the DataReader object as the source
       // for the "dgsuperheroes" datagrid
       dgsuperheroes.DataSource = objReader;
       dgsuperheroes.DataBind();
 
       // free up memory
       objReader.Close();  
}
</script>
<html>
<body>
<asp:datagrid id="dgsuperheroes" runat="server" />
</body>
</html>

Assuming that a table called superheroes exists in your local MS-SQL database, here is the output you should see. After importing the required .NET libraries for accessing a MS-SQL database, the custom BindMe() function is invoked on page load. This function uses the SqlDataReader object to retrieve the data from the superheroes table. And the rest is routine: Assign the DataReader object as the data source of the DataGrid object, and bind the two with a call to the DataBind() method, as shown earlier.

The result of the script above is a rendering of the contents of the database table in neat little rows and columns. Notice the amount of code required to generate this output: zero, if you exclude the bits required to authenticate against the database. Using a DataGrid can thus save you significant time and effort when all you need is a quick-and-dirty way of rendering the records in a database result set.

Makeup time
As shown above, the default browser output of the DataGrid is as exciting as watching grass grow. So let's get out the lawn mover and manicure the yard—oops, the DataGrid—by adding a bunch of optional attributes to the DataGrid server control. These attributes, used wisely, can help in making your data look neater and more colorful.
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<script Language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {   
 
       // invoke the custom "BindMe" function
       // to bind the datagrid with the data
       BindMe();
}
 
// function to bind the records retrieved
// from the database to my "dgsuperheroes" datagrid
void BindMe() {
 
       // build the connection string
       string strConn = "user id=sa;password=sa;";
       strConn += "initial catalog=pubs;data source=mydbserver;";
      
       // connect to the database
       SqlConnection objConn = new SqlConnection(strConn);
      
       // create an instance of the DataReader object
       SqlCommand objCommand = new SqlCommand("SELECT * FROM superheroes;", objConn);
       objConn.Open();
       SqlDataReader objReader = objCommand.ExecuteReader();
      
       dgsuperheroes.DataSource = objReader;
       dgsuperheroes.DataBind();
 
       objReader.Close();  
}
</script>
<html>
<body>
<asp:datagrid id="dgsuperheroes" runat="server" Width = "700"  BackColor = "#DFDFDF" BorderColor = "#FF0000" BorderStyle = "dotted" ForeColor = "#000000" BorderWidth = "2" CellPadding = "10"  CellSpacing = "5">
       <HeaderStyle BackColor="#000000" ForeColor="#FFFFFF"/>
       <AlternatingItemStyle BackColor="#C0C0C0" />
</asp:datagrid>
</body>
</html>

You can see a screenshot of the output here. How did I manage this amazing transformation? Well, here's a list of the attributes I've added to the plain-vanilla DataGrid control. Take a look at the explanations (some of them will already be familiar to you from regular HTML), and you'll see just how easy it is.
  • The Width attribute controls the width of the grid.
  • The BackColor attribute controls the background color.
  • The BorderColor attribute controls the color of the border around the grid.
  • The BorderStyle attribute controls the style of the border around the grid.
  • The ForeColor attribute controls the text color.
  • The BorderWidth attribute controls the width of the border around the message area.
  • The CellPadding attribute controls space between the text and borders of each cell.
  • The CellSpacing attribute controls spacing between the cells of the grid.
  • The HeaderStyle element allows you to specify a custom style for the first row of your grid—very useful if you want to highlight different headings for your tabular data. You can specify a FooterStyle also, if required. Finally, the AlternatingItemStyle element allows you to customize the appearance of alternate rows by adding color and font elements to them.

Report pagination
One of the most common things developers have to do when dealing with large record sets is writing code to navigate between "pages" of the data. This is usually complex and can take a fair amount of time to code. With the DataGrid, automatic paging is just a few function calls away, as demonstrated in Listing A.

You can see the output from page 1 here. In this example, I've used the SqlDataAdapter object to move through the result set, as well as the following DataGrid attributes, which are intended specifically for paging:
  • The AllowPaging attribute is a Boolean that is set to "True" if you want paging.
  • The PageSize attribute stores the number of records that you want to display on each page.
  • The PagerStyle-Mode attribute allows you to define the mechanism for displaying the paging mechanism. Valid values include "NumericPages" and "NextPrev."
  • The OnPageIndexChanged attribute specifies the event handler to be invoked when the user navigates to the next set of records using the paging mechanism.

From the code and attribute descriptions above, it's clear that when the user clicks one of the paging links, the dgsuperheroes_NextPage() function is invoked. This resets the value of the CurrentPageIndex property of the DataGrid to display the next or previous set of records. All that you, as the developer, need to do is remember to increment or decrement the page index; the DataGrid takes care of all the other little calculations and adjustments for you.

Editor's Picks