Reputation: 5417
I have a method that does some work on a DataTable e.g.
private void MyMethod(DataTable table)
{
if(table.Rows.Count > 0)
{
// do some work
}
}
However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.
I have also tried . . .
if(table.IsInitialized) { }
and
if(table != null) { }
but I get the same error message.
How do I test to see if the incoming datatable is instantiated and not null please?
The DataTable is coming from a cast of a datagrid in a WinForms app i.e.
DataTable table = (DataTable)datagridview.DataSource;
So the issue arises if the original datagridview is empty.
Upvotes: 3
Views: 5507
Reputation: 9804
You get the "reference not set to a instance of object" exception if you got a case like this:
object someObject = null;
//Throws an exception. You try to call a instance function without specify the instance
someObject.ToString();
So either table is null or rows returns null. Prior to C# 6.0 you have to go the hard way:
if(table != null && table.Rows != null && table.Rows.Count > 0)
I assumed count was not a nullable Integer. If it was, you have to check for it being null too of course.
At least for debugging, you might want to write that code a bit more verbose with a "one operation per line" rule. That would help you locate which operation exactly returns null. And the JiT will most likely cut out the temporary variables outside of debug runs anyway.
//If table is null, exception here
var Row = table.Row;
//If Row is null, Exception here.
var Count = Row.Count;
//Nothing is null. Continue.
if(Count > 0);
With C# 6.0, you got the new Null conditional operator to write it a bit shorter: https://msdn.microsoft.com/en-us/library/dn986595.aspx It is still the same code, however.
Upvotes: 4
Reputation: 131
I know this is a couple years old question, but there is an easy way to solve this right now in C# as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)
Upvotes: 0
Reputation: 56433
How do I test to see if the incoming datatable is instantiated and not null please?
Technically, this should work and if the code below does not detect whether table
is instantiated or not then there is another problem aside from the one at hand.
if(table != null && table.Rows != null && table.Rows.Count > 0)
Upvotes: 0
Reputation:
table != null
should work.
Here's an example:
using System;
using System.Data;
public class Program
{
public static void Main()
{
DataTable table = null;
Test(table);
table = new DataTable();
Test(table);
}
public static void Test(DataTable table)
{
if(table == null)
{
Console.WriteLine("table is null");
return;
}
if(table.IsInitialized == false)
{
Console.WriteLine("table is not initalised.");
return;
}
Console.WriteLine("table row count: " + table.Rows.Count);
}
}
Output:
table is null
table row count: 0
https://dotnetfiddle.net/0s2Jp8
Upvotes: 2