group-logo
Jan 28, 2012

Grouping Data in ASP.NET Gridview Control

In my previous post, I explained how to group HTML table rows with jQuery. This post explains How to do same thing using ASP.NET Gridview control on server side. The logic is same to check row by row. If data is same in next row’s cell, hide next row’s cell and increase rowspan of current row’s cell.

HTML:

 <asp:GridView ID="GridView1" runat="server" CellPadding="4">
 </asp:GridView>

asp.net gridview grouping rows

Server Side:

I have created a generalize method ‘GroupGridView‘ to group data in the gridview.

void GroupGridView(GridViewRowCollection gvrc, int startIndex, int total)
    {
        if (total == 0) return;
        int i, count = 1;
        ArrayList lst = new ArrayList();
        lst.Add(gvrc[0]);
        var ctrl = gvrc[0].Cells[startIndex];
        for (i = 1; i < gvrc.Count; i++)
        {
            TableCell nextCell = gvrc[i].Cells[startIndex];
            if (ctrl.Text == nextCell.Text)
            {
                count++;
                nextCell.Visible = false;
                lst.Add(gvrc[i]);
            }
            else
            {
                if (count > 1)
                {
                    ctrl.RowSpan = count;
                    GroupGridView(new GridViewRowCollection(lst), startIndex + 1, total - 1);
                }
                count = 1;
                lst.Clear();
                ctrl = gvrc[i].Cells[startIndex];
                lst.Add(gvrc[i]);
            }
        }
        if (count > 1)
        {
            ctrl.RowSpan = count;
            GroupGridView(new GridViewRowCollection(lst), startIndex + 1, total - 1);
        }
        count = 1;
        lst.Clear();
    }

You have to pass 3 parameters:
gvrc: GridView Rows
startIndex: index of first column to be grouped(where to start grouping).
total: total number of columns to be grouped.

How to Use:

Before using this method, Make sure data is sorted in same order in which they are to be grouped. Bind the gridview and Pass the gridview rows, start index and total number of columns to be grouped in GroupGridView method and enjoy it.

	GridView1.DataSource = GetDataTable();
        GridView1.DataBind();
        GroupGridView(GridView1.Rows, 0, 3);
 

The above code will group first 3 columns of gridview.

Hope, It’ll save your time.

  • Bosscoder

    Thanks! Very, very useful!

  • Adilsuza

    Thank You

  • nahush

    nice

  • Happy

    Thank you very much! I was looking for it for hours!

  • RationalEnvironmentalist

    This is an excellent piece of work that saved me hours.

    Many thanks

  • Lara Medha

    that was too gud… it saved a lot of time to me

  • amit gajjar

    Thanks a lot, this code works for me and help me to same my time… keep contributing.,…. and best luck

  • Mustafa Albstanje

    Thanks , Very very much

  • Fábio Medeiros Bitencourt

    Thank you so much, you’re saved.