Checking for null value in a field
I am reading data in a row using DataRow object. If there is null data in the column, then the following line of code is crashing. How can I check to see the content of the field is null before I do any other operation?
aDataRow.ItemArray[1].ToString() //fails because there is null value and Tostring() may not work.
If there is no Null value in this field, I want to convert that value to double. that part works.
Convert.ToDouble(aDataRow.ItemArray[1].ToString())
thanks
nath
Re: Checking for null value in a field
There are all sorts of things wrong with that code.
Firstly, that is an incorrect usage of the ItemArray property. Every time you access the ItemArray property a new array is created. For that reason you should never be accessing the ItemArray property more than once. If you want to use it then you assign it to a variable and then access it via that variable, so that you're using the same array object every time.
Code:
object[] items = aDataRow.ItemArray;
string item1 = items[1].ToString();
string item2 = items[2].ToString();
Secondly, there should be no reason to call the ToString method of the object. You should be casting it as the type it is. If it is a string then cast it as string. If it's a double then cast it as double.
Thirdly, if you only want to access a single field then you should generally be just indexing the DataRow directly:
Code:
double item = (double)aDataRow[1];
So finally, if you need to get a double from a field of a DataRow that might contain a null value it will be something like:
Code:
if (!aDataRow.IsNull(1))
{
// The field at index 1 is not null.
double item = (double)aDataRow[1];
}