Merge gridview cells in ASP.Net

PreRender Event of a control is a very useful event in ASP.Net. This is the event which will be called just before the control rendered to the client browser and modification done to the control in this stage of life cycle will reflect in the browser.

For example, lets take a gridview in to consideration. We know that a gridview always follows a columnar or tabular structure. Now one may ask -what is columnar or tabular structure..Ok, for now I am just sharing a line. Columnar structure means data in the gridview to be arranged only in a column basis view or table basis view. In fact when are binding a gridview, it is just rendering the rows present in the datasource in the manner we have defined its header cells. You can’t find a data of a column in  another column normally.

Yes, we are here to change this basic idea. We don’t have any real control to the structure of gridview till the Databinding event. Although we have certain process to change the structure of the gridview on RowDataBound, but I still feel it is more easy and convenient way to do the changes on gridview PreRender  event. The cause for suggesting this is- on this event we have a ready made structure and we need to check for necessary logic and do the changes.

For gridview cells merge, I am using following method to be called inside gridview PreRender event.

Here, the int array contains all the column indices that are to be merged on same data if found.

public void MergeCell(int[] colIndices)
foreach (int colIndex in colIndices)
for (int rowIndex = gvSchoolList.Rows.Count - 2; rowIndex >= 0; rowIndex--)
GridViewRow row = gvSchoolList.Rows[rowIndex];
GridViewRow previousRow = gvSchoolList.Rows[rowIndex + 1];
if (row.Cells[colIndex].Text == previousRow.Cells[colIndex].Text)
row.Cells[colIndex].RowSpan = previousRow.Cells[colIndex].RowSpan < 2 ? 2 : previousRow.Cells[colIndex].RowSpan + 1;
previousRow.Cells[colIndex].Visible = false;

And finally you will get a result like this-

Gridview with merged cells


2 thoughts on “Merge gridview cells in ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s