Results 1 to 4 of 4

Thread: Handling NULL datetime values

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2001
    Posts
    153

    Handling NULL datetime values

    Hi

    How would I handle this.

    The code is below

    DateTime invoicedate = ((DateTime)invoiceReader["inv_date"]);

    If the inv_date is returned NULL from the database I get the following error.

    System.InvalidCastException: Specified cast is not valid.

    Any ideas how to resolve this error?

    VK
    there r no alternatives 4 hardwork.

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

    Re: Handling NULL datetime values

    vb Code:
    1. If invoiceReader.IsDBNull("inv_date") Then
    2.     'The inv_date column contains a null value.
    3. Else
    4.     Dim invoiceDate As Date = CDate(invoiceReader("inv_date"))
    5. End If
    or:
    vb Code:
    1. Dim invoiceDate As Nullable(Of Date)
    2.  
    3. If invoiceReader.IsDBNull("inv_date") Then
    4.     invoiceDate = Nothing
    5. Else
    6.     invoiceDate = CDate(invoiceReader("inv_date"))
    7. End If
    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

  3. #3
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Handling NULL datetime values

    Moved to C#

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

    Re: Handling NULL datetime values

    Now I'll answer in C#:
    Code:
    if (invoiceReader.IsDBNull("inv_date"))
    {
        // The inv_date column contains a null value.
    }
    else
    {
        DateTime invoiceDate = invoiceReader["inv_date"];
    }
    or:
    Code:
    Nullable<DateTime> invoiceDate;
    
    if (invoiceReader.IsDBNull("inv_date"))
    {
        invoiceDate = null;
    }
    else
    {
        invoiceDate = invoiceReader["inv_date"];
    }
    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