Question

I am retrieving DateTime data from an access data base and want to assign it to an object as a string value.

OleDbDataReader dbRead = cmd.ExecuteReader();
while (dbRead.Read())
{
    product.DateReleased = dbRead["Date Released"] != DBNull.Value ? (string)dbRead["DATE"] : "No Date available";
    product.DatePublished = dbRead["Publish_Date"] != DBNull.Value ? (string)dbRead["Publish_Date"] : "No Date Available"; 
}

The property of the Product object is a string value and the value I am retrieving from the database is DateTime.

Trying to run the process gives me an InvalidCastException exception and I have a feeling it is because of a parsing issue.

Advice perhaps on where the problem is?

Regards

Was it helpful?

Solution

DateTime and string are different data types, and can't be casted to each other, like int and float. You need to parse string in order to retrieve DateTime. Try to use next code snippet to try to Parse DateTime with default format, provided in current culture.

OleDbDataReader dbRead = cmd.ExecuteReader();
 while (dbRead.Read())
 {
     product.DateReleased = dbRead["Date Released"] != DBNull.Value ? DateTime.Parse(dbRead["DATE"]) : null;
     product.DatePublished = dbRead["Publish_Date"] != DBNull.Value ? DateTime.Parse(dbRead["Publish_Date"]) : null; 
 }

Assuming DatePublished and DateReleased is of type DateTime?. If you have specific date format, you can use DateTime.ParseExact method, which takes format as a parameter, for example

DateTime.ParseExact(dbRead["Date Released"], "dd.MM.yyyy", CultureInfo.InvariantCulture)

If DatePublished and DateReleased are of type string, then you should call ToString() on a DateTime, to convert it to string, like:

product.DateReleased = dbRead["Date Released"] != DBNull.Value ? dbRead["DATE"].ToString() : "No Date available";
product.DatePublished = dbRead["Publish_Date"] != DBNull.Value ? dbRead["Publish_Date"].ToString() : "No Date Available";

If the underlying column in your database has a DateTime type, you can access GetDateTime method on the OleDbDataReader class, like

product.DateReleased = dbRead.GetDateTime("Date Released");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top