Click here to Skip to main content
15,499,289 members
Articles / Web Development / ASP.NET
Posted 10 Jan 2009


71 bookmarked

GroupedGridview - A Customized GridView Control

Rate me:
Please Sign up or sign in to vote.
4.83/5 (30 votes)
10 Jan 2009CPOL2 min read
Grouping repeated data in a GridView control.


This article is all about creating a custom GridView control which is useful in scenarios where the data is in a hierarchical format, e.g., for columns like Country, State, etc., or Manager, Employee, etc.


Sample Data

Grouped Image with Grouped Depth 2

Grouped Data

In the above scenarios, rather than using the GridView, GroupedGridview can be used in which the repetition of data is avoided.


Users having a knowledge of creating an inherited (custom) control can easily use/understand this article.

Quickly learn how to create an inherited (custom) control

It's just like adding any other control like a Button or a DataGrid. First, create a new Class Library project. Create a class and derive it from an existing class. E.g.: TextBox, Button etc. In this article, we have derived from a GridView class.

Then, write the functionality which you want to add. This includes overriding methods, etc. Once you are done with it, create its DLL. Add a reference to the DLL in the web application.

Now, you are ready to customize the Toolbox: Right-click the Toolbox, .NET Framework Components, Browse, select the newly created DLL, and click OK. Then, you will notice the new control added in the Toolbox. It's now ready to use.

Using the code

The main part of this article is the class GroupedGridView which inherits from the GridView class.

/// <summary />
/// Summary description for GroupedGridView
/// </summary />
namespace CommonClassLibrary
    public class GroupedGridView : GridView

The class has a property GroupedDepth which specifies the number of columns needed to be grouped.

public int GroupedDepth
        object val = this.ViewState["GroupedDepth"];
        if (null == val)
            return 0;

        return (int)val;
        if (value < 0)
            throw new ArgumentOutOfRangeException....
        this.ViewState["GroupedDepth"] = value;

The GroupedGridView class overrides GridView's OnDataBound event, in which a recursive function SpanCellsRecursive is called.

protected override void OnDataBound(EventArgs e)
    this.SpanCellsRecursive(0, 0, this.Rows.Count);

The function below loops through the row data and compares the column values. The compared value will be stored in a boolean variable isNewGroup. If the variable value is true, then its RowSpan is set to 1. And, if its value is false, the cell's Visible property is set to false and the RowSpan is incremented, thus duplicate display is avoided.

private void SpanCellsRecursive(int columnIndex, int startRowIndex, int endRowIndex)
    if (columnIndex >= this.GroupedDepth || columnIndex >= this.Columns.Count)

    TableCell groupStartCell = null;
    int groupStartRowIndex = startRowIndex;

    for (int i = startRowIndex; i < endRowIndex; i++)
        TableCell currentCell = this.Rows[i].Cells[columnIndex];

        bool isNewGroup = (null == groupStartCell) || 
            (0 != String.CompareOrdinal(currentCell.Text, groupStartCell.Text));

        if (isNewGroup)
            if (null != groupStartCell)
                SpanCellsRecursive(columnIndex + 1, groupStartRowIndex, i);

            groupStartCell = currentCell;
            groupStartCell.RowSpan = 1;
            groupStartRowIndex = i;
            currentCell.Visible = false;
            groupStartCell.RowSpan += 1;

Once the class is added in the class library, add a reference to the DLL and the control will be available in the Toolbox ready to add in the web application, as mentioned in the Background part of the article above. The newly created control on your webpage looks like this:

<%@ Page Language="C#" AutoEventWireup="true" 
   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="CommonClassLibrary" 
   Namespace="CommonClassLibrary" TagPrefix="cc1" %>

<html xmlns="">
<head  runat="server">
    <title>Untitled Page</title>
    <form id="form1"  runat="server">
        <cc1:GroupedGridView ID="GroupedGridView1"  runat="server" 
          BackColor="White" BorderColor="#CCCCCC"
          BorderStyle="None" BorderWidth="1px" 
          CellPadding="3" GroupedDepth="2" AutoGenerateColumns="false">
             <columns />
                <asp:BoundField HeaderText="Country" DataField="Country" />
                <asp:BoundField HeaderText="Country Code" DataField="Code" />
                <asp:BoundField HeaderText="State" DataField="State" />
             </columns />


Note: This control does not work for AutoGenerateColumns="true". Sorry about that. I am working on this issue.

//Binding the dataset to the Gridview
GroupedGridView1.DataSource = dataSet;


This is my first article here. I hope you find this article and control useful - it's saved me a lot of time when working with several different types of hierarchical data, to quickly get a full-featured GridView grouped control up and running. Enjoy!

Any suggestions and feedback for improvement are highly appreciated!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
India India
Bachelor Of Computer Engineering - Working as a Microsoft Developer for past 10+ years.

Has experience in C#.NET, ASP.NET MVC, JavaScript/jQuery, AngularJS, Telerik, NUnit, SQL Server 2012, SSIS, SSAS.

Comments and Discussions

GeneralMy vote of 3 Pin
Vikas Mann4-Nov-14 5:17
MemberVikas Mann4-Nov-14 5:17 
GeneralMy vote of 5 Pin
AJMAL SHAHZAD13-Nov-12 19:09
MemberAJMAL SHAHZAD13-Nov-12 19:09 
BugCannot get RowCreated to work Pin
profnachos11-Dec-11 19:20
Memberprofnachos11-Dec-11 19:20 
GeneralNice idea! Pin
Sandeep Mewara28-Mar-10 9:50
mveSandeep Mewara28-Mar-10 9:50 
Generalgridview grouping Pin
danishjee29-Mar-09 1:20
Memberdanishjee29-Mar-09 1:20 
GeneralNice work Pin
Mike Ellison12-Feb-09 12:03
MemberMike Ellison12-Feb-09 12:03 
GeneralRe: Nice work Pin
sudhanvag12-Feb-09 22:50
Membersudhanvag12-Feb-09 22:50 
Generalnice Pin
jeshonhe15-Jan-09 8:49
Memberjeshonhe15-Jan-09 8:49 
GeneralRe: nice Pin
sudhanvag15-Jan-09 22:36
Membersudhanvag15-Jan-09 22:36 
GeneralAutoGenerateColumns doesn't work Pin
andre_monteiro15-Jan-09 5:54
Memberandre_monteiro15-Jan-09 5:54 
GeneralRe: AutoGenerateColumns doesn't work [modified] Pin
sudhanvag16-Jan-09 0:05
Membersudhanvag16-Jan-09 0:05 
GeneralRe: AutoGenerateColumns doesn't work Pin
andre_monteiro16-Jan-09 0:09
Memberandre_monteiro16-Jan-09 0:09 
GeneralRe: AutoGenerateColumns doesn't work [modified] Pin
sudhanvag16-Jan-09 1:28
Membersudhanvag16-Jan-09 1:28 
Generalvb.NET translation Pin
BrendanSaunders12-Jan-09 21:12
MemberBrendanSaunders12-Jan-09 21:12 
GeneralRe: vb.NET translation Pin
sudhanvag12-Jan-09 21:34
Membersudhanvag12-Jan-09 21:34 
GeneralGood Job !! Pin
Abhijit Jana11-Jan-09 1:08
professionalAbhijit Jana11-Jan-09 1:08 
GeneralRe: Good Job !! Pin
sudhanvag11-Jan-09 2:20
Membersudhanvag11-Jan-09 2:20 
GeneralSuggestion and Feedback Pin
sudhanvag10-Jan-09 4:57
Membersudhanvag10-Jan-09 4:57 
GeneralRe: Suggestion and Feedback Pin
Dr.Luiji10-Jan-09 11:48
professionalDr.Luiji10-Jan-09 11:48 
GeneralRe: Suggestion and Feedback Pin
sudhanvag10-Jan-09 16:50
Membersudhanvag10-Jan-09 16:50 
GeneralRe: Suggestion and Feedback Pin
Anurag Gandhi19-Oct-10 23:17
professionalAnurag Gandhi19-Oct-10 23:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.