datagrid cells addrow?

  • Thread starter Thread starter Craig Buchanan
  • Start date Start date
C

Craig Buchanan

Is there a way to add a row to a datagrid during the ItemDataBound event? I
would like to add a 'header' row before the start of a group of rows.

Thanks,

Craig Buchanan
 
I created a function to handle the "grouping":

Private Sub GroupHeader(ByVal Item As
System.Web.UI.WebControls.DataGridItem)

Dim tc As TableCell = New TableCell

tc.ColumnSpan = "4"

tc.Text = Item.Cells(3).Text & "[" & Item.ItemIndex & "]"

tc.ForeColor = System.Drawing.Color.White

tc.BackColor = System.Drawing.Color.Firebrick

Dim dgi As DataGridItem

If Item.ItemType = ListItemType.Item Then

dgi = New DataGridItem(2, 0, ListItemType.Item)

ElseIf Item.ItemType = ListItemType.AlternatingItem Then

dgi = New DataGridItem(2, 0, ListItemType.AlternatingItem)

End If

dgi.Cells.Add(tc)

DataGrid1.Controls(0).Controls.AddAt(2, dgi)

End Sub

I call this function in the ItemDataBound event if the itemtype is an
alternatingitem or an Item

Unfortunately, the new rows don't show up where I'd expect.

Can anyone explain what the first two arguments of the DataGridItem
constructor really mean? Also, if I add a row, does that change the
ItemIndex of the bound Item?

Thanks,

Craig
 
Solved it:

Private Sub GroupHeader(ByVal Item As
System.Web.UI.WebControls.DataGridItem)

Static LastItem As System.Web.UI.WebControls.DataGridItem 'track the
last item
Static Groups As Integer 'track number of group rows added to
datagrid

If (Not LastItem Is Nothing) Then
'compare text value in prior row to text in current row (change cell as
appropriate)
'if text value hasn't changed, still in same group, exit
If LastItem.Cells(3).Text = Item.Cells(3).Text Then Exit Sub
End If

'increment group counter
Groups += 1

'create a new cell with appropriate properties
Dim tc As TableCell = New TableCell
tc.ColumnSpan = "4" 'span the table
tc.Text = Item.Cells(3).Text
tc.ForeColor = System.Drawing.Color.White
tc.BackColor = System.Drawing.Color.Firebrick

'create a new row. probably doesn't matter with listittemtype
Dim dgi As DataGridItem
If Item.ItemType = ListItemType.Item Then
dgi = New DataGridItem(0, 0, ListItemType.Item)
ElseIf Item.ItemType = ListItemType.AlternatingItem Then
dgi = New DataGridItem(0, 0, ListItemType.AlternatingItem)
End If

'add cell to new row
dgi.Cells.Add(tc)

'add row to datagrid; use group counter to correctly position row (each row
that is added
increments the ItemIndex)
DataGrid1.Controls(0).Controls.AddAt(Item.ItemIndex + Groups, dgi)

'store this item to be use in next pass
LastItem = Item

End Sub
 
Back
Top