14

How can I check if a DataTable has never been set, meaning it will be Null or Nothing? I don't mean an empty DataTable.

For example:

Dim dt As DataTable = TryCast(Session("dt"), DataTable)

If dt.Rows.Count <> 0 Then
    'Do something !
End If 

If Session("dt")has never been set or is lost in memory for some reason, dt.Rows.Count <> 0 will throw this exception:

Object reference not set to an instance of an object.

Bugs
  • 4,491
  • 9
  • 32
  • 41
Laurence
  • 7,633
  • 21
  • 78
  • 129
  • For anyone else finding this and wants to know more check out the answers at [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Bugs Mar 24 '17 at 08:54

3 Answers3

19

Preferred:

If dt Is Nothing Then ...

or (VB6 like)

If IsNothing(dt) Then ...

IsNothing Function

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

dt2 = datatable If dt2.Rows.Count > 0

Estus
  • 1
-1

If the value datatype is varbinary(MAX), use

if dt.rows(0).item(2) Is DBNull.Value then...
ain
  • 1
  • 1
    Please re-read the question. It explicitly asks to check when a `DataTable` has not been set. That means your code will fail. – Bugs Mar 24 '17 at 08:47