Merge GridView Header Columns

Continuing my ASP.NET GridView Tips and Tricks series, here’s another one that shows how to create a merged column in a GridView Header.

The code shown here is based on my previous post Bind ASP.NET GridView to a Custom Object or Collection with Paging and Sorting. In this example, we will add a RowCreated event to the GridView as shown below:

<asp:GridView ID="gvCustom" runat="server" AutoGenerateColumns="false"
AllowPaging="true" PageSize="5" OnPageIndexChanging="gvPaging"

Finally write the following code in the RowCreated event


protected void gvCustom_RowCreated(object sender,
GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.Header)
GridView header = (GridView)sender;
GridViewRow gvr = new GridViewRow(0, 0,
TableCell tCell = new TableCell();
tCell.Text = "DevCurry Employee Information";
tCell.ColumnSpan = 4;
tCell.HorizontalAlign = HorizontalAlign.Center;
// Add the Merged TableCell to the GridView Header
Table tbl = gvCustom.Controls[0] as Table;
if (tbl != null)
tbl.Rows.AddAt(0, gvr);

VB.NET (Converted Code)

Protected Sub gvCustom_RowCreated(ByVal sender As Object,
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Header Then
header As GridView = CType(sender, GridView)
Dim gvr As New GridViewRow(0, 0, DataControlRowType.Header,
Dim tCell As New TableCell()
tCell.Text = "DevCurry Employee Information"
tCell.ColumnSpan = 4
tCell.HorizontalAlign = HorizontalAlign.Center
' Add the Merged TableCell to the GridView Header
Dim tbl As Table = TryCast(gvCustom.Controls(0), Table)
If tbl IsNot Nothing Then
tbl.Rows.AddAt(0, gvr)
End If
End If
End Sub

In the code above, we have created a TableCell and set properties like the ColumnSpan (for merging columns), Text and HorizontalAlign. The TableCell is then added to the GridView Header.



Read some more GridView Tips and Tricks over here

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


sami said...

Very Useful , THX for sharing.

Saran said...

Really awesome man...Good post