How to check if a Datatable is Null or Nothing

lawphotog picture lawphotog · Apr 26, 2012 · Viewed 74.3k times · Source

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.

Answer

Tim Schmelter picture Tim Schmelter · Apr 26, 2012

Preferred:

If dt Is Nothing Then ...

or (VB6 like)

If IsNothing(dt) Then ...

IsNothing Function