Link to home
Start Free TrialLog in
Avatar of cookiejar
cookiejarFlag for United States of America

asked on

String was not recognized as a valid DateTime error on Convert.ToDateTime

I loading values from the database to a dataset.  When there is a null in the datetime column, the FormatException  is thrown - String was not recognized as a valid DateTime.  How do I handle this problem in the following method.

 public dsInventory PopulateClass(DataSet ds)
        {
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            dsInventory dsI = new dsInventory();
            foreach (DataRow dtrow in dt.Rows)
            {
                //Error on these lines when a null is available
                dsI.MtlDueDate = Convert.ToDateTime(dtrow["MtlDueDate"].ToString());
                dsI.MtlReceiptDate = Convert.ToDateTime(dtrow["MtlReceiptDate"].ToString());
                         

            }
            return dsI;
          }
ASKER CERTIFIED SOLUTION
Avatar of Angelp1ay
Angelp1ay
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:
   if (! DBNull.Value.Equals(row[fieldName]))
   {
      //not null
   }
   else
   {
      //null
   }
If you want your field to be a plain DateTime instead of the Nullable DateTime (DateTime?) I proposed then you need to do what ChloesDad said and probably want to set your field to DateTime.MinValue.

Personally I think DateTime? represents your data semantics more correctly.
Avatar of Dmitry G
First, you may need to check values for DbNull:

if (row["myCol"] != DBNull.Value)
{
         ... //some code
}
else
{

}

Open in new window


In 'else' you may set your dateTime value to DateTime.MinValue or DateTime.MaxValue instead.

Other option would be to use Nullable of DateTime.
Declaring as like below ., will accept the nothing in date field
Try like this in your code and check
 
 Dim DOB As Nullable(Of Date) = Date.Now
    DOB = Nothing

Open in new window