Quantcast
Channel: TechBrij
Viewing all articles
Browse latest Browse all 116

Grouping Data in ASP.NET Gridview Control

$
0
0


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>

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.

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.

Related posts:

  1. HTML Table Row Grouping with jQuery
  2. Displaying Total in ASP.NET Gridview Footer Row Without using Template Field
  3. Adding Gridview nested in Repeater in ASP.NET 2.0
  4. Bind array to specific column of asp.net gridview
  5. Create Dynamic DropDownLists in asp.net

Viewing all articles
Browse latest Browse all 116

Trending Articles