指定的强制转换无效

本文关键字:转换 无效 | 更新日期: 2023-09-27 18:26:36

我有一个从数据库中获取日期时间值的应用程序,但它给了我这个错误

指定的强制转换不是有效的

这是代码

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();

我该如何解决这个问题?

指定的强制转换无效

您应该使用:

var Date = Convert.ToDateTime(n3["YOUR_DATE_COLUMN"]);
sql日期不是.Net DateTime对象。

GetSqlDateTime不进行转换—请参阅MSDN。

它必须转换-请参阅SO问题作为的示例