I am querying a SQL Server table to get a value that is of the datatype datetime in the table.
The item in the database is this: 2014-05-17 23:52:09.333
The following code throws this exception:
Unable to cast object of type 'System.DateTime' to type 'System.String'.
Code:
internal List<string> CustomSqlQuery(string dbName, string dbTable, string dbColumn, string query, string connString)
{
var databaseItems = new List<string>();
var conn = new SqlConnection(connString);
var cmd = new SqlCommand(query, conn);
try
{
using (cmd)
{
conn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// exception thrown on the following line
// Unable to cast object of type 'System.DateTime' to type 'System.String'.
var item = reader.GetString(reader.GetOrdinal(dbColumn));
databaseItems.Add(item);
}
}
}
conn.Close();
}
catch (Exception exception)
{
Logger.Log(Loglevel.Error, "Boom: {0}", exception.Message);
return null;
}
return databaseItems;
}
How do you convert the datetime into a string?