Results 1 to 2 of 2

Thread: Checking for null value in a field

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2003
    Posts
    436

    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

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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];
    }
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width