Span columns in Gridview header

By Ken Fitzpatrick

Sometimes you need the header in a gridview to label columns in groups instead of labeling each individual column. One way to do this is to set the colspan property on a header cell and remove the following cells. You can do this in the RowCreated event. Instead of removing the cells, you need to remove the column object from the controls collection. Each control renders into a <td></td>. The code is shown in this post.

'For each ShoppingItem in this example, the grid displays three columns.
'We want the labels in the header row to span those three columns.

Private Sub gvDisplay_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvDisplay.RowCreated
    'If the rowtype is a header
    If e.Row.RowType = DataControlRowType.Header Then
        'Starting with the first column, we need to span 3 columns, and remove the others from the header
        Dim n as Integer = 0
        For Each i As ShoppingItem In _items
            'Set the cell's colspan to 3 (will render as <td colspan=3>")
            e.Row.Cells(n).ColumnSpan = 3
             'Modify other things like text and width
            e.Row.Cells(n).Text = i.Name
            e.Row.Cells(n).Width = New System.Web.UI.WebControls.Unit(80)
            'Now remove the next two column controls from the header
            'They render into <td> statements. We don't need them after the colspan.
            e.Row.Controls.RemoveAt(n + 1)
            e.Row.Controls.RemoveAt(n + 1)
             'Advance to the next column in the header
            n += 1
        Next
    End If
End Sub

Related FAQs

The following is snippet of code from a RowDataBound event handler for a Gridview named Gridview1. To change the background color of a Gridview row, you need to add a handler for the RowDataBound event. This event is called for each row added to a datagrid whem it is being bound from the datasource. Use the condition "If e.Row.RowType = DataControlRowType.DataRow" to only trap when a data row is being written as opposed to a header row or footer row.
Span columns in Gridview header  (1286 Views)
Create New Account