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

2 comments: