To read the article online, visit http://www.4GuysFromRolla.com/articles/040502-1.aspx

An Extensive Examination of the DataGrid Web Control: Part 1

By Scott Mitchell


The First in a Multi-Part Series
This article is the first in a multi-part series on using the DataGrid Web control that will span several weeks. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is highly versitile. In its simplest form (examined in this article) the DataGrid displays a bare-bones HTML table, but it can be enhanced to output a richer UI, to allow for sorting based on the database columns, and to even allow paging of the database results! All of these interesting topics will be covered in future parts of this article series.

  • Read Part 2
  • Read Part 3
  • Read Part 4
  • Read Part 5
  • Read Part 6
  • Read Part 7
  • Read Part 8
  • Read Part 9
  • Read Part 10
  • Read Part 11
  • Read Part 12
  • Read Part 13
  • Read Part 14
  • Read Part 15
  • Read Part 16
  • Read Part 17
  • Read Part 18
  • Introduction


    One of the most common tasks in classic ASP was retrieving tabular information from a database and displaying it in an HTML table. With classic ASP this would require many lines of intermixed HTML and code; the following pseudocode shows what the code would commonly look like:

    Create Database Connection
    Populate a recordset based on some SQL query
    Output the HTML table header (<table ...>)
    Loop through the recordset
      Emit the HTML for a table row
      ...
    Emit the HTML table footer (</table>)

    If you're an ASP developer chances are you've written code like above more times than you'd care to admit! One of the advantages of ASP.NET is that it contains a number of Web controls. These Web controls, which emit HTML, provide a programmatic interface, allowing developers to separate code and content and treat these HTML emitting entities as objects in their code. That is, if we wanted to display some HTML content using ASP.NET we'd do the following:

    <script language="vb" runat="server">
      sub Page_Load(sender as Object, e as EventArgs)
        lblMessage.Text = "Hello, World!"
      end sub
    </script>
    
    <asp:label runat="server" id="lblMessage" />
    

    Here the label Web control lblMessage is placed in the HTML using HTML-like tags with the runat="server" attribute specified. Then, in the Page_Load event handler (which is run every time the page is loaded) the Text property of the lblMessage Web control is set to "Hello, World!" The use of Web controls here separates the code from the content; in classic ASP one would need to place a <%="Hello, World!"%> in the proper place within the HTML content to achieve the same effect.

    There are ASP.NET Web controls that are much more useful and powerful than the simple label control. The DataGrid Web control, which we'll be dissecting in this article, is one such powerful control. The DataGrid emits the needed HTML for data-bound HTML tables. As we'll soon see, binding data to a DataGrid is very easy; furthermore, with only a few slight property changes you can customize the look and feel the DataGrid's output, rendering very professional looking HTML tables (a feat when one considers my utter lack of artistic skill!).

    DataGrid Basics


    To place a DataGrid on an ASP.NET Web page you simply need to add the following code:

    <asp:datagrid runat="server" id="ID_of_DataGrid" />

    Here the id you choose will be the name of the DataGrid you'll use when referring to it in your server-side code. The syntax above gets us started using a DataGrid by placing it in the HTML content, but in order to have the DataGrid display anything useful we need to bind the DataGrid to some collection of information. This collection of information can be any object that supports the IEnumerable interface. This includes things like Arrays, collection classes (ArrayList, Hashtable, etc.), DataSets, DataReaders, and a number of other objects. Since we'd like to focus on displaying database information, for this article we'll focus on binding DataGrids to DataReaders, which are synonymous to forward-only, firehose cursors Recordsets in classic ADO/ASP. (For more information on reading database results into DataReaders using ADO.NET be sure to read: Efficiently Iterating Through Results from a Database Query using ADO.NET.)

    So, how do we go about binding data to the DataGrid? It's amazingly simple. The first thing we need to do is to grab a DataReader containing some database data. For this example I am hitting the ASPFAQs.com database and bringing back the ten most popular FAQs. Once I have this data in a DataReader, to bind it to my DataGrid I just need to write two lines of code. The first line sets the DataGrid's DataSource property to the DataReader; the second line calls the DataGrid's DataBind method. That's all there is to it, as the following code snippet shows.

    <% @Import Namespace="System.Data" %>
    <% @Import Namespace="System.Data.SqlClient" %>
    <script language="vb" runat="server">
      Sub Page_Load(sender as Object, e as EventArgs)
        BindData()
      End Sub	
    	
      Sub BindData()
        '1. Create a connection
        Dim myConnection as New SqlConnection(
              ConfigurationSettings.AppSettings("connectionString"))
    
        '2. Create the command object, passing in the SQL string
        Const strSQL as String = "sp_Popularity"
        Dim myCommand as New SqlCommand(strSQL, myConnection)
    
        'Set the datagrid's datasource to the datareader and databind
        myConnection.Open()
        dgPopularFAQs.DataSource = myCommand.ExecuteReader(
                                  CommandBehavior.CloseConnection)
        dgPopularFAQs.DataBind()	
      End Sub
    </script>
    
    <asp:datagrid id="dgPopularFAQs" runat="server" />
    
    [View a live demo!]

    First off note that the amount of code we have to write to utilize databinding is not much at all. We essentially create a connection, specify a SQL command (in this case a stored procedure, sp_Popularity), open the database connection, set the DataGrid's DataSource property to the resulting DataReader, and finally call the DataGrid's DataBind method. This approach completely isolates the code from the content; there's no mixing of HTML table and DataReader output syntax, as we would have had with classic ASP.

    Take a moment to view the live demo. You'll notice that the DataGrid displays the database contents in a plane-Jane HTML table - it's pretty ugly. While the main "work" has been done for us (displaying the data), there's a lot to be desired on the user-interface front. Fortunately, prettying up the DataGrid results is amazingly easy. Unfortunately, this will have to wait for the next part of this article series! Stay tuned! :-)

    Summary


    In this part of the series on DataGrid usage, we examined the very basics of DataGrids - how to plop one down on an ASP.NET Web page and display bound database results. Unfortunately the DataGrid's output is not pretty. However, as we'll soon see, prettying up the display of the DataGrid is a breeze. Additionally, we'll look at more advanced UI options (such as paging database results, sorting the DataGrid's results on the fly, and other cool stuff) in upcoming portions of this article.

    Happy Programming!

  • By Scott Mitchell

  • Article Information
    Article Title: ASP.NET.An Extensive Examination of the DataGrid Web Control: Part 1
    Article Author: Scott Mitchell
    Published Date: April 5, 2002
    Article URL: http://www.4GuysFromRolla.com/articles/040502-1.aspx


    Copyright 2014 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers