Monday, 6 February 2012

Grouping Data in ASP.NET Gridview Control


Grouping Data in ASP.NET Gridview Control


HTML:

?
1
2
<asp:GridView ID="GridView1" runat="server" CellPadding="4">
</asp:GridView>
gridview grouping rows aspdotnet Grouping Data in ASP.NET Gridview Control

Server Side:

I have created a generalize method ‘GroupGridView‘ to group data in the gridview.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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.

No comments :