A Simple way to span column headers in an asp.net Gridview
Let’s say you have an asp.net gridview and you want to group or span several columns under the same heading. For example, you are displaying quarterly sales data:
| Customer | Rep | Q1 Sales | Q2 Sales | Q3 Sales | Q4 Sales |
| Acme Tools | John Smith | 4500 | 4400 | 4600 | 4100 |
| Mega Motors | Anne Tyler | 9790 | 9670 | 9540 | 8900 |
But what you really want to show is:
| Sales | |||||
| Customer | Rep | Q1 | Q2 | Q3 | Q4 |
| Acme Tools | John Smith | 4500 | 4400 | 4600 | 4100 |
| Mega Motors | Anne Tyler | 9790 | 9670 | 9540 | 8900 |
If your Gridview is called grdSales, there is an easy way to do this in the code behind. Create an event for row_created, then put this in:
Protected Sub grdSales_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdSales.RowCreated
If e.Row.RowType = DataControlRowType.Header Then
Dim oGridView As GridView = DirectCast(sender, GridView)
Dim oGridViewRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
Dim oTableCell As New TableCell()
oTableCell.Text = “”
oTableCell.ColumnSpan = 2
oTableCell.BackColor = Drawing.Color.White
oGridViewRow.Cells.Add(oTableCell)
oTableCell = New TableCell()
oTableCell.Text = “Sales”
oTableCell.HorizontalAlign = HorizontalAlign.Center
oTableCell.ColumnSpan = 4
oGridViewRow.Cells.Add(oTableCell)
oGridView.Controls(0).Controls.AddAt(0, oGridViewRow)�
End If
End Sub
If you found my post helpful and it saved you time or money, please contribute by making a small donation. Even a dollar or two adds up!
Suripunj said,
Very Informative
Add A Comment