Datagridd's Bound Event

prav_roy

Well-known member
Joined
Sep 10, 2005
Messages
70
Location
Mumbai
Programming Experience
1-3
hi,
i am binding my datagrid to datatable..and in my datagrid there are four columns.. what i want to do is that i want to check each value of column(1) and if it is not null i want to display that columns value in red i am using the following code...

Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
Dim dat As String = CType(DataBinder.Eval(e.Item.DataItem, "Zee TV"), String)
If dat <> "" Then
e.Item.ForeColor = System.Drawing.Color.Red
End If
End If
End Sub

but problem is that.. some values in that column are null and its gives me an error saying

Cast from type 'DBNull' to type 'String' is not valid.

can anybody help me on this.. its bit urgent

Thannk you in advance
 
hi Paszt,
Thank you for your reply.. i am bit confused as where to add this code..should i add this line before or after
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then

thank you
 
Try this inside your databind routine....

VB.NET:
If e.Item.ItemType = ListItemType.AlternatingItem Or 
   e.Item.ItemType = ListItemType.Item Then
      If e.Item.DataItem.Equals(System.DbNull.Value) OR _
         e.Item.Cells(0).Text <> "" Then
                 e.Item.ForeColor = System.Drawing.Color.Red
       EndIf
EndIf
Just remember that datagrid columns are zero indexed so 0 is the first column. This should fall into your text as red for both NULLS and BLANKS.
 
Back
Top