Merge Header – GridView/DataGrid


During development with GridView, we might come across many situations in which we need to extend theGridView for our requirements. For example, we might need to have a separate header other than the default header provided by GridView. In that case, we need to add a new GridView item of type Header. In this article, we will see how to merge two or more columns in a GridView.


In this example, we have a simple GridView which fetches data from an XML file and displays that in the table structure. In this GridView, we need to add two additional headers with text “Department” and “Employee”. The department column should occupy the first two columns and the Employee column should occupy the rest of the three columns.


I found in the internet that there are many ways to do this, but we might end up with column alignment issues.


Here, we are going to see one of the best methods to do this. To have an additional header, we need to add aGridViewRow of type Header to the GridView inside the OnRowCreated event. Here is the code snippet for doing this:

 Collapse | Copy Code
protected void GridView_Merge_Header_RowCreated(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.Header)
        //Build custom header.
        GridView oGridView = (GridView)sender;
        GridViewRow oGridViewRow = new GridViewRow(0, 0, 
                    DataControlRowType.Header, DataControlRowState.Insert);
        TableCell oTableCell = new TableCell();

                //Add Department
                oTableCell.Text = "Department";
                oTableCell.ColumnSpan = 2;

                //Add Employee
                oTableCell = new TableCell();
                oTableCell.Text = "Employee";
                oTableCell.ColumnSpan = 3;
                oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);

Code for DataGrid (VS.NET 1.0/1.1)

 Collapse | Copy Code
Private Sub DataGrid1_ItemCreated(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
        Handles DataGrid1.ItemCreated
    If e.Item.ItemType = ListItemType.Header Then
        Dim dgItem As DataGridItem
        Dim dgCell As TableCell
        dgItem = New DataGridItem(0, 0, ListItemType.Header)
        dgCell = New TableCell()
        dgCell.ColumnSpan = 2
        dgCell.Text = "List of Products"
        DataGrid1.Controls(0).Controls.AddAt(0, dgItem)
    End If
End Sub

That’s it.

Posted in: Blog

Leave a Comment (0) ↓

Leave a Comment