DataGrid with SubHeadings

This demo illustrates how to have a DataGrid display subheadings for changing categories.


Product NameUnit PriceStock Level
Beverages
Chai18.0039
Chang19.0017
Guaraná Fantástica4.5020
Sasquatch Ale14.00111
Steeleye Stout18.0020
Côte de Blaye263.5017
Chartreuse verte18.0069
Ipoh Coffee46.0017
Laughing Lumberjack Lager14.0052
Outback Lager15.0015
Rhönbräu Klosterbier7.75125
Lakkalikööri18.0057
Condiments
Aniseed Syrup10.0013
Chef Anton's Cajun Seasoning22.0053
Chef Anton's Gumbo Mix21.350
Grandma's Boysenberry Spread25.00120
Northwoods Cranberry Sauce40.006
Genen Shouyu15.5039
Gula Malacca19.4527
Sirop d'érable28.50113
Vegie-spread43.9024
Louisiana Fiery Hot Pepper Sauce21.0576
Louisiana Hot Spiced Okra17.004
Original Frankfurter grüne Soße13.0032
Confections
Pavlova17.4529
Teatime Chocolate Biscuits9.2025
Sir Rodney's Marmalade81.0040
Sir Rodney's Scones10.003
NuNuCa Nuß-Nougat-Creme14.0076
Gumbär Gummibärchen31.2315
Schoggi Schokolade43.9049
Zaanse koeken9.5036
Chocolade12.7515
Maxilaku20.0010
Valkoinen suklaa16.2565
Tarte au sucre49.3017
Scottish Longbreads12.506
Dairy Products
Queso Cabrales21.0022
Queso Manchego La Pastora38.0086
Gorgonzola Telino12.500
Mascarpone Fabioli32.009
Geitost2.50112
Raclette Courdavault55.0079
Camembert Pierrot34.0019
Gudbrandsdalsost36.0026
Flotemysost21.5026
Mozzarella di Giovanni34.8014
Grains/Cereals
Gustaf's Knäckebröd21.00104
Tunnbröd9.0061
Singaporean Hokkien Fried Mee14.0026
Filo Mix7.0038
Gnocchi di nonna Alice38.0021
Ravioli Angelo19.5036
Wimmers gute Semmelknödel33.2522
Meat/Poultry
Mishi Kobe Niku97.0029
Alice Mutton39.000
Thüringer Rostbratwurst123.790
Perth Pasties32.800
Tourtière7.4521
Pâté chinois24.00115
Produce
Uncle Bob's Organic Dried Pears30.0015
Tofu23.2535
Rössle Sauerkraut45.6026
Manjimup Dried Apples53.0020
Longlife Tofu10.004
Seafood
Ikura31.0031
Konbu6.0024
Carnarvon Tigers62.5042
Nord-Ost Matjeshering25.8910
Inlagd Sill19.00112
Gravad lax26.0011
Boston Crab Meat18.40123
Jack's New England Clam Chowder9.6585
Rogede sild9.505
Spegesild12.0095
Escargots de Bourgogne13.2562
Röd Kaviar15.00101


Source Code
<%@ Page Language="VB" autoeventwireup="false" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="System.Drawing" %>
<script runat="server">

    Sub Page_Load(Sender As Object, E As EventArgs) Handles MyBase.Load

           ' TODO: Update the ConnectionString and CommandText values for your application
           Dim ConnectionString As String = ConfigurationSettings.AppSettings("connectionStringNW")
           Dim CommandText As String = "Select CategoryName, ProductName, Cast(UnitPrice as  varchar(50)) as unitprice, UnitsinStock from Products INNER JOIN Categories On Products.categoryID = Categories.CategoryID order by Products.categoryID"

           Dim myConnection As New SqlConnection(ConnectionString)
           Dim myCommand As New SqlDataAdapter(CommandText, myConnection)

           Dim ds As New DataSet
           myCommand.Fill(ds)

    'Before DataBind - Add New Rows Here for Each Sub Heading
           Dim curCat As String
           Dim prevCat As String
           Dim row As TableRow
           Dim i As Integer = 0

           Do While i <= ds.Tables(0).Rows.Count - 1
               curCat = ds.Tables(0).Rows(i).Item("CategoryName")
               If curCat <> prevCat Then
                   prevCat = curCat
                   Dim shRow As DataRow = ds.Tables(0).NewRow
                   shRow("ProductName") = ds.Tables(0).Rows(i).Item(0)
                   shRow("UnitPrice") = "SubHead"
                   ds.Tables(0).Rows.InsertAt(shRow, i)
                   
                   i += 1
               End If
               
               i += 1
           Loop
           'End Insert SubHeadings

           DataGrid1.DataSource = ds
           DataGrid1.DataBind()

       End Sub

       Private Sub DataGrid1_ItemDataBound(sender As Object,  e As DataGridItemEventArgs)
           Select Case e.Item.ItemType
               Case ListItemType.AlternatingItem, ListItemType.Item
                   If e.Item.Cells(1).Text.Equals("SubHead") Then
                       'Format the data, and then align the text of each cell to the left.
                       e.Item.Cells(0).Attributes.Add("align", "Left")
                       e.Item.Cells(0).ColumnSpan = 3
                       e.Item.Cells(0).Font.Bold = True
                       e.Item.Cells.RemoveAt(2)
                       e.Item.Cells.RemoveAt(1)
                       e.Item.BackColor = Color.FromArgb(204,204,255)
                   End If
           End Select
       End Sub

</script>

    <form runat="server">
        <asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" EnableViewState="False" ForeColor="Black" BackColor="White" CellPadding="3" GridLines="None" CellSpacing="1" OnItemDataBound="DataGrid1_ItemDataBound">
            <HeaderStyle font-bold="True" forecolor="White" backcolor="#4A3C8C"></HeaderStyle>
            <ItemStyle backcolor="#DEDFDE"></ItemStyle>
            <Columns>
                <asp:BoundColumn DataField="ProductName" HeaderText="Product Name"></asp:BoundColumn>
                <asp:BoundColumn DataField="UnitPrice" HeaderText="Unit Price"></asp:BoundColumn>
                <asp:BoundColumn DataField="UnitsInStock" HeaderText="Stock Level"></asp:BoundColumn>
            </Columns>
        </asp:datagrid>
    </form>


[Return to the article...]