Ok, I’ve been hacking around this particular problem for a month now, but think I’ve got a bead on how to stop it. So, I hope this helps someone!
The Situation
I’ve got a TableAdapter in C# and I’m using a Query to return a scalar value that ultimately becomes a double data type. The trouble is that if the query returns a NULL, I get the error:
‘NullReferenceException was unhandled by user code’
Here’s the code that gives me the error:
myTableAdapters.myTableAdapter ta = new myTableAdapters.myTableAdapter(); double median = (double)ta.GetMedianLineItems();
When I hit a null, it crashes.
The Solution
What I want to happen is to ‘continue’ in my loop if I get a null. In my case, and the code I’ll show below, it’s acceptable to continue if I get ’0′. Here’s the code that works in my case:
myTableAdapters.myTableAdapter ta = new myTableAdapters.myTableAdapter();
double median = Convert.ToDouble(ta.GetMedianLineItems());
if (median == 0)
{
return;
}
Using the ‘System.Convert’ object prevents the crash. Convert gives you a long list of data types you can attempt to convert to: dates, decimals, doubles, int’s, booleans, strings, chars, etc, etc.
A really handy method of Convert is IsDBNull, which will let you check a value in a datatable before you try to assign it to a variable and get a null error.
Nulls, for being a whole lot of nothing, can be a real PITA.
Cheers,
Byron



