简体   繁体   中英

Specified cast is not valid

I have an application that get a datetime value from the database but it give me this error

Specified cast is not valid

here is the code

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Golden_RoseConnectionString"].ConnectionString);

con.Open();
String sel3 = "select Booking_Date from booking where Booking_ID='" + Booking_Id + "'";
SqlCommand cmd3 = new SqlCommand(sel2, con);
SqlDataReader n3 = cmd3.ExecuteReader();
n3.Read();
DateTime Booking_Date = (DateTime)n3.GetSqlDateTime(0);
con.Close();

How can I solve this problem?

an sql date is not a .Net DateTime object.

GetSqlDateTime does not do a convertion - see MSDN .

It must be converted - see the SO question as an example

您应该使用:

var Date = Convert.ToDateTime(n3["YOUR_DATE_COLUMN"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM