Using the DataGrid's ItemCreated event on PostBack

S

Stephen Miller

I have a DataGrid with a series of transactions and wish to highlight
negative value items in red. This is simple on the initial DataBind,
by using the ItemDataBound event to format the ListItemType based on a
DataItem's value. Ie:

Private Sub myGrid_ItemDataBound(ByVal sender As Object, _
ByVal e As DataGridItemEventArgs) Handles myGrid.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
If CType(e.Item.DataItem("Balance"), Decimal) < 0 Then
e.Item.ForeColor = System.Drawing.Color.Red
End If
End If
End Sub

On the initial page load this code would work equally well in the
DataGrid's ItemCreated event. Ie:

Private Sub myGrid_ItemCreated (ByVal sender As Object, _
ByVal e As DataGridItemEventArgs) Handles myGrid.ItemCreated
If e.Item.ItemType = ListItemType.Item Then
If CType(e.Item.DataItem("Balance"), Decimal) < 0 Then
e.Item.ForeColor = System.Drawing.Color.Red
End If
End If
End Sub

However, on PostBack, the DataGrid is rebuilt from ViewState and only
the ItemCreated event is raised. My problem is that when the DataGrid
is rebuilt the original DataItem's appear to be unavailable. The
myGrid_ItemCreated method above fails on PostBack at the line:

If CType(e.Item.DataItem("Balance"), Decimal) < 0 Then
...

Placing a watch on the value e.Item.DataItem("Balance") reveals that
is has no value.

I had though I could refer to the actual data in the cell, where
(assuming the 'Balance' is in the first column):

If CType(e.Item.Cells(0).Text, Decimal) < 0 Then
...

However this also has no value (presumably because the Item hasn't
actually been created yet).

Similarly, using a TemplateColumn and placing the 'Balance' in a Label
and then usinging FindControl to retrieve the value also fails. Ie:

Dim lblBalance As Label = e.Item.FindControl("lblBalance")
If CType(lblBalance.Text, Decimal) < 0 Then
...


So the problem is, how do I parse a variable or condition in a
DataGrid that can be used in the ItemCreated event on PostBack to
provide custom formatting to the grid?

Thanks,

Stephen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top