Friday, June 13, 2008

Dynamically Adding multiple row header to a datagrid

To add a row to a datagrid header dynamically use following code. Here we just adding new cells to the the datagrid at header ItemDataBound Event.

#VB.Net code:

Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal ev As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid.ItemDataBound ' Add a second header on a datagrid
If ev.Item.ItemType = ListItemType.Header Then ' Get the collection of cells from the datagrid
Dim totCells As TableCellCollection
' Get the collection of existing cells so we can get a count
totCells = ev.Item.Cells
' Create a new datagrid header object
Dim dgHeader As New DataGridItem(0, 0, ListItemType.Header) ' Add the created cell to the header
Dim vblCount As Integer
Dim vblCounter As Integer
vblCount = totCells.Count
vblCounter = 0
While vblCount > 0

'Creation of a new cell for datagrid
Dim CreatedCell As New TableCell
'To skip first cell of our grid
If vblCounter > 1 Then
CreatedCell.Text = "Text for New Cell"
End If

dgHeader.Cells.Add(CreatedCell)

vblCounter = vblCounter + 1
vblCount = vblCount - 1

End While
'While Closes here

dgHeader.Visible = True ' Add the header to the datagrid
DataGrid.Controls(0).Controls.Add(dgHeader)
End If
' If ends here
End Sub ' ItemDataBound Ends here

No comments: