cookiejar
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 "].ToStrin g());
dsI.MtlReceiptDate = Convert.ToDateTime(dtrow[" MtlReceipt Date"].ToS tring());
}
return dsI;
}
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["
dsI.MtlReceiptDate = Convert.ToDateTime(dtrow["
}
return dsI;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
Personally I think DateTime? represents your data semantics more correctly.
First, you may need to check values for DbNull:
In 'else' you may set your dateTime value to DateTime.MinValue or DateTime.MaxValue instead.
Other option would be to use Nullable of DateTime.
if (row["myCol"] != DBNull.Value)
{
... //some code
}
else
{
}
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
Try like this in your code and check
Dim DOB As Nullable(Of Date) = Date.Now
DOB = Nothing
Here's an example:
if (! DBNull.Value.Equals(row[fi
{
//not null
}
else
{
//null
}