When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips

Book Reviews
Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
Web Hosts
Author an Article

Print this Page!
Published: Monday, June 10, 2002

An Extensive Examination of the DataGrid Web Control: Part 5

By Scott Mitchell

The Fifth Part in a Multi-Part Series
This article is the fifth piece of 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 versatile. The basics of the DataGrid were discussed in Part 1; information on specifying display properties of the DataGrid was discussed in Part 2. In Part 3 we examined how to associate custom events with the DataGrid. In Part 4 we looked at how to extend Part 3 to provide custom sorting on the results of a DataGrid. In this part we look at how to provide further custom UI support when displaying DataGrid results through the use of TemplateColumns.

  • 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
  • - continued -

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start is author Scott Mitchell's most recent book, which thoroughly examines three of the most commonly used ASP.NET Web controls: the DataGrid, DataList, and Repeater. These three Web controls can be difficult to master due to their numerous features and capabilities. With this book, you'll quickly become an expert, learning the gritty details and true capabilities of each. This 400+ page book explores the topics in this article series in much greater depth, along with examining various topics and techniques not covered here.

    Scott Mitchell is the editor and founder of 4GuysFromRolla.com, author of the An Extensive Examination of the DataGrid Web Control article series, and author of numerous other ASP and ASP.NET books.

    [Buy this Book]
    [Visit the Book's Companion Web Site]


    In Part 2 we examined how to customize the DataGrid's output through the use of BoundColumn controls. By setting the DataGrid's AutoGenerateColumns property to False, we could specifically indicate what database columns should appear in the DataGrid, their column's header text, and formatting and style information, all through a BoundColumn control. While this approach is very powerful and allows for very customized renderings of data, it is limiting in the sense that the output is encased in a simple TD HTML tag, making it a standard HTML table column in the DataGrid.

    What if you wanted more flexibility, though? Along with the DataGrid control, ASP.NET contains the DataList and Repeater Web controls, which allow you to customize the specific HTML output through the use of HeaderTemplates, ItemTemplates, and FooterTempaltes. Essentially, a template allows you to specify HTML and data bound values that appear in the header, in each item, of in the footer, respectively. The DataGrid supports this functionality on a per-column basis. That is, in a DataGrid, in the <Columns> tag, we can specify to place TemplateColumns instead of BoundColumns for a much finer grain of control in the DataGrid's HTML output. In this article we'll examine the basics of the TemplateColumn and how to use them to customize the DataGrid output.

    Using a TemplateColumn

    With the DataGrid you can specify TemplateColumns on a per-Column basis. As with BoundColumns, to use TemplateColumns you need to set the DataGrid's AutoGenerateColumns to False first. Then, you can place a TemplateColumn control in the <Columns> tag for each templated column you wish to display. Note that you can also have BoundColumns in the <Columns> tag as well; that is, a DataGrid may be made up of both BoundColumns and TemplateColumns, as the following example illustrates:

    <asp:datagrid id="dgPopularFAQs" runat="server"
        <asp:BoundColumn DataField="FAQID" ItemStyle-Width="10%" 
    			ItemStyle-HorizontalAlign="Center" HeaderText="FAQ ID" />
        <asp:TemplateColumn HeaderText="FAQ Information">

    The above DataGrid would have two columns for each row: one a BoundColumn (FAQID) and the other a TemplateColumn, whose content we've yet to specify. (For more information on BoundColumns be sure to read Part 2 of this article.) Also note that you could have multiple TemplateColumns - all a TemplateColumn control does is generate one column for each row in the DataGrid. The HTML output for that row is specifies by tags inside of the TemplateColumn control, as we will see shortly.

    So, how does one specify the HTML content for a TemplateColumn? The TemplateColumn control itself has some UI-related properties, such as HeaderText, which specifies the HTML content to appear in the column's header, and Visible, which specifies if the column is rendered or not. More interestingly are the tags that can appear inside of the TemplateColumn. There are four such tags:

    1. ItemTemplate - specifies the template for each row for the particular column the TemplateColumn represents.
    2. HeaderTemplate - specifies the template for the column's header.
    3. FooterTemplate - specifies the template for the column's footer.
    4. EditItemTemplate - specifies the template for the a cell of a particular row that has been selected for editing. This can occur when using the DataGrid's Edit/Update/Delete features (which we've yet to cover in this article series... see this ASP.NET QuickStart example for more information).

    These templates can contain vanilla HTML as well as data-bound values. For example, a very simple TemplateColumn might simply output the value of a database column in bold text. (Yes, yes, a BoundColumn could be used here, of course.) To output a dynamic data value from the DataGrid's DataSource, use the following syntax:

    <%# DataBinder.Eval(Container.DataItem, "ColumnName") %>

    This is known as a "databinding" command. Essentially it says, "Find the ColumnName column in the DataItem (the DataItem being the current row of the DataGrid's DataSource - by current I mean, the DataGrid is looping through the specified DataSource (most likely a DataReader or a DataSet), and at each loop iteration it must render a row of the DataGrid.

    Hence, our DataGrid's TemplateColumn would contain an ItemTemplate with a single line of code (the databinding statement shown above), which would look like:

    <asp:TemplateColumn HeaderText="FAQ Information">
        <b><%# DataBinder.Eval(Container.DataItem, "ColumnName") %></b>

    The Benefits of a TemplateColumn over a BoundColumn

    At this point you may not fully realize the UI freedoms granted to you by the TemplateColumn. In fact, our simple example above could have easily been implemented by a BoundColumn. But what if you wanted to show two database column values in one DataGrid column? You could not do this in a BoundColumn, yet this task is painfully simple with a TemplateColumn.

    Let's look at a more complex example. In all of the previous demos I've included with this article series I've been showing the 10 most popular FAQs from ASPFAQs.com. Of course I've been using BoundColumns all along, so each column in the DataGrid's output has had only one specific database value. Imagine, however, that I wanted to have the DataGrid's output to have just two columns in total. The first column would list the FAQ's ID (FAQID), while the second column would contain inside of it an HTML table of its own, which would display the Category Name, Description, and ViewCount of the particular FAQ. Using TemplateColumns, this is fairly simple, as can be seen by the code below:

    <asp:datagrid id="dgPopularFAQs" runat="server"
        <asp:BoundColumn DataField="FAQID" ItemStyle-Width="10%" 
    			ItemStyle-HorizontalAlign="Center" HeaderText="FAQ ID" />
        <asp:TemplateColumn HeaderText="FAQ Information">
            <table border="0">
                <td align="right"><b>Description:</b></td>
                <td><%# DataBinder.Eval(Container.DataItem, "Description") %></td>
                <td align="right"><b>Category Name:</b></td>
                <td><%# DataBinder.Eval(Container.DataItem, "CatName") %></td>
                <td align="right"><b>View Count:</b></td>
                <td><%# DataBinder.Eval(Container.DataItem, "ViewCount", "{0:#,###}") %>
    [View a live demo!]

    Note that the last data-bound statement uses an alternate form of DataBinder.Eval - it included an optional third parameter that specifies a format string for the column. The formatting string #,### specifies that ever three digits should be separated by a comma. (The {0:formatString} syntax may seem a bit confusing - it simply states that the formatting string formatString should be applied to the 0th argument (i.e., the value housed in the current DataItem's ViewCount column).


    In this article we examined how to use a TemplateColumn to provide a finer grain of control over a DataGrid's cell's HTML output. Clearly the TemplateColumn control allows for a much greater degree of flexibility in HTML output than the BoundColumn control. Additionally, as we will see in future articles, the TemplateColumn control can be used to customize the look of a DataGrid row when the user opts to edit the row. Very cool stuff indeed!

    Happy Programming!

    By Scott Mitchell

    ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article