Group rows in Gridview

You may want to show some grouped rows with header in gridview and display as the following

I didn’t post the code how to retrieve the dataset or object collection and bind to gridview as the data source, only show the two major part code which can implement the solution.

Step 1. Override the gridview render event

protected override void Render(HtmlTextWriter writer)
    string lastSubCategory = String.Empty;
    Table gridTable = (Table)gvProducts.Controls[0];
    foreach (GridViewRow gvr in gvProducts.Rows)
        HiddenField hfSubCategory = gvr.FindControl("hfSubCategory") as
        string currSubCategory = hfSubCategory.Value;
        if (lastSubCategory.CompareTo(currSubCategory) != 0)
            int rowIndex = gridTable.Rows.GetRowIndex(gvr);
            // Add new group header row
            GridViewRow headerRow = new GridViewRow(rowIndex, rowIndex,
                DataControlRowType.DataRow, DataControlRowState.Normal);
            TableCell headerCell = new TableCell();
            headerCell.ColumnSpan = gvProducts.Columns.Count;
            headerCell.Text = string.Format("{0}:{1}", "SubCategory",
            headerCell.CssClass = "GroupHeaderRowStyle";
            // Add header Cell to header Row, and header Row to gridTable
            gridTable.Controls.AddAt(rowIndex, headerRow);
            // Update lastValue
            lastSubCategory = currSubCategory;

Step 2. create a hidden field “hfSubCategory” in the aspx page

<asp:gridview id="gvProducts"
  emptydatatext="No data available."
  runat="server" DataKeyNames="ProductID"
  <AlternatingRowStyle CssClass="AlternatingRowStyle" />
  <HeaderStyle CssClass="ColumnHeaderStyle" />
    <asp:BoundField DataField="ProductID" HeaderText="Product ID">
        <ItemStyle Width="200px"/>
    <asp:BoundField DataField="Name" HeaderText="Product Name”>
        <HeaderStyle HorizontalAlign="Left"/>
        <ItemStyle Width="200px" HorizontalAlign="Left"/>
    <asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />
    <asp:BoundField HeaderText="Price"
        <ItemStyle HorizontalAlign="Right"></ItemStyle>
            <asp:HiddenField ID="hfSubCategory" runat="server"
                             Value='<%#Eval("SubCategoryName")%>' />


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s