Reputation: 372
I have a method that retrieves all data from a specific column in a table. Now this method works when the fields are in "string" or "int" (by changing to GetInt32) formats in the database, although it doesn't like date fields, my method is as follows:
public static void getDates()
{
//create the database connection
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\ev_mgr.mdb");
//create the command object and store the sql query
OleDbCommand actorCommand = new OleDbCommand("select Issue_Time2 from Events", aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader aReader = actorCommand.ExecuteReader();
//Iterate throuth the database
while (aReader.Read())
{
timeList.Add(aReader.GetString(0)); // Error occurs here
}
//close the reader
aReader.Close();
//close the connection Its important.
aConnection.Close();
}
//Some usual exception handling
catch (OleDbException e)
{
Console.WriteLine("Error: {0}", e.Errors[0].Message);
}
foreach (string time in timeList)
{
Console.WriteLine(time);
}
}
An exception is thrown on this line:
timeList.Add(aReader.GetString(0));
Error:
Specified cast is not valid.
An example of a date/field in the column is:
02/05/2012 15:52:45
Upvotes: 0
Views: 2187
Reputation: 48558
Use
timeList.Add(DateTime.Parse(aReader.GetString(0)).ToString(yourdateformat));
where yourdateformat can be "dd/mm/yyyy hh:MM:ss"
or whatever you want
Upvotes: 0