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>
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.
Thanks, that was very helpful man!
This is working fine when the column is having normal text, if i am trying to group it by a hyperlink column its always is displaying the first value and that is the only one group
Good work… !
This is very helpful and working smoothly. Thank you! :)
Thank you so much, you’re saved.
Thanks , Very very much
Thanks a lot, this code works for me and help me to same my time… keep contributing.,…. and best luck
that was too gud… it saved a lot of time to me
This is an excellent piece of work that saved me hours.
Many thanks
Thank you very much! I was looking for it for hours!
Thank You
nice
Thanks! Very, very useful!