Saturday, August 8, 2009

Merge GridView Cells Or Columns in Row ASP.NET C#

During writing of my last post on the Custom Pager for GridView Control I have found very interesting article on merging the cells of the grid view control. In this post I will continue my work of Custom Pager for GridView Control, and extend it to merge the cells of the gridview control. I have used same source example of the Custom Pager for GridView Control post.
Here is the code which is used to merge the cell of the grid view control after the grid view control is filled with data, the code below is written in the databound event of the grid view control.

for (int intRowIndex = grdvCustomer.Rows.Count - 2; intRowIndex >= 0; intRowIndex--)
GridViewRow gvCurrnteRow= grdvCustomer.Rows[intRowIndex];
GridViewRow gvPreviousRow = grdvCustomer.Rows[intRowIndex + 1];
for (int intCellCount = 0; intCellCount < gvRow.Cells.Count; intCellCount++)
if (gvCurrnteRow.Cells[intCellCount].Text == gvPreviousRow.Cells[intCellCount].Text)
if (gvPreviousRow.Cells[intCellCount].RowSpan < 2)
gvCurrnteRow.Cells[intCellCount].RowSpan = 2;
gvCurrnteRow.Cells[intCellCount].RowSpan = gvPreviousRow.Cells[intCellCount].RowSpan + 1;
gvPreviousRow.Cells[intCellCount].Visible = false;
In the above code the logic of merging the cells is simple one. The for loop start from the second last row of the grid. Next is to declare the two GridViewRow objects by storing the second last and the last row from the grid view rows. Next is to compare the text of both the row and if the text both rows are equal then check the if the rowspan of the gvCurrentRow if it is less then 2 then assign it to 2 and if it is greater then 2 then assign the rowspan plus 1 of the previous row to the gvCurrentRow object and at the end set visible property of the gvpreviouse object to false.You can download the source code from here.

1- Merge GridView Cells Or Columns in Row ASP.NET C# VB.NET

All and any comments / bugs / suggestions are welcomed!


Anonymous said...

How to add & display check box in each multiple cells and save it to database

MB said...

Hi there.
I am using the same code to achieve merge functionality of gridview cells. But everytime I run the page, the last row cells of the gridview are not merged even if the last and previous last row have identical data in some cells.
Request your help. Thanks.

Anonymous said...

customizing gridview columns in c#