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"
OnRowCreated="gvCustom_RowCreated">

Finally write the following code in the RowCreated event

C#

protected void gvCustom_RowCreated(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView header = (GridView)sender;
GridViewRow gvr = new GridViewRow(0, 0,
DataControlRowType.Header,
DataControlRowState.Insert);
TableCell tCell = new TableCell();
tCell.Text = "DevCurry Employee Information";
tCell.ColumnSpan = 4;
tCell.HorizontalAlign = HorizontalAlign.Center;
gvr.Cells.Add(tCell);
// 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
Dim
header As GridView = CType(sender, GridView)
Dim gvr As New GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert)
Dim tCell As New TableCell()
tCell.Text = "DevCurry Employee Information"
tCell.ColumnSpan = 4
tCell.HorizontalAlign = HorizontalAlign.Center
gvr.Cells.Add(tCell)
' 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.

OUTPUT

image

Read some more GridView Tips and Tricks over here






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Unknown said...

Very Useful , THX for sharing.

Saran said...

Really awesome man...Good post