Click here to Skip to main content
15,895,988 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a window form AND i want to retrieve datetime from database, there was an error specifeid cast is not valid
Posted
Updated 8-Jan-14 22:20pm
v2
Comments
phil.o 9-Jan-14 4:21am    
Incomplete : please show the code you have, describe the database table involved (particularly the field that causes the problem) and specify which line does throw the exception.

1 solution

The problem is that there are a huge number of ways that you could have got this wrong!
The most obvious one is that you are storing your DateTime values in your database in a NVARCHAR column instead of a DATE or DATETIME columns, and then doing something like this:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT dateEntered FROM myTable", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                DateTime entered = (DateTime) reader["dateEntered"];
                ...
                }
            }
        }
    }
Because your DB column is string based, the SqlReader returns a string value, which cannot be cast to a DateTime - you would have to use DateTime.Parse or Datetime.TryParse.

But don't. Change your database to store Date based values in DateTime fields. It makes workign with them a whole lot easier...
 
Share this answer
 
Comments
Gandalf_TheWhite 9-Jan-14 4:43am    
5, Correct Answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900