1

I am not vb.net expert, but made to work on it for now. Retrieving value for database, which in some cases Is NULL for a datetime column (Sql database). When it is retrieved in vb.net using something like this.

 select testcolumn from testtable

and result converted to datatable. the value fails validation(even though the retrieved value in database is null)

If Not dt("testcolumn") Is Nothing

End If

Ideally this validation is point for me which decides whether the value should be assigned to a property for class. but as this fails.next exception I get is Invalid cast, as i try to do something Like

myClass.datetimeProperty=dt("testcolumn").ToString()

Any reason for this, and is only way to perform additional validation of

If Not string.isnullOrEmpty(dt("testcolumn)
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
Mandar Jogalekar
  • 3,199
  • 7
  • 44
  • 85
  • Check on DBNull.Value – Fabian Bigler Feb 27 '15 at 07:16
  • 1
    possible duplicate of [handling dbnull data in vb.net](http://stackoverflow.com/questions/222834/handling-dbnull-data-in-vb-net) –  Feb 27 '15 at 07:17
  • (It's admittedly not an exact duplicate, but that looks like a good canonical question to me, and is broad enough to also cover your question.) –  Feb 27 '15 at 07:18
  • If `dt` is actually a [`DataRow`](https://msdn.microsoft.com/en-us/library/system.data.datarow(v=vs.110).aspx) class, then that contains a separate `IsNull` method to check for nullability. – Damien_The_Unbeliever Feb 27 '15 at 08:11

1 Answers1

2

Instead of checking on Nothing, you have to check on DBNull.Value.

If dt("testcolumn") IsNot DbNull.Value
'your code
End If

Or another alternative:

If NOT IsDbNull(dt("testcolumn")) Then
   'your code
End If
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70