Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidCastException: Specified cast is not valid

I retrieve a table from the database that contains a column of type "time" in sql server, and I try to assign this to a DateTime variable but i get this error: System.InvalidCastException: Specified cast is not valid.

here's my c# code:

DateTime StartTime = (DateTime)dt.Rows[i]["startTime"];

knowing that the column "startTime" is of type "time" and I can change it in the database. any help??

like image 319
Sherif El Nady Avatar asked Feb 20 '26 00:02

Sherif El Nady


2 Answers

DateTime StartTime = Convert.ToDateTime(dt.Rows[i]["startTime"].ToString());

And if you know that it could be null..

DateTime StartTime = (dt.Rows[i]["startTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dt.Rows[i]["startTime"].ToString()));
like image 153
Marcosvoda Avatar answered Feb 21 '26 12:02

Marcosvoda


You should be able to cast it as a TimeSpan:

var startTime = dt.Rows<TimeSpan>("startTime");
like image 36
James Johnson Avatar answered Feb 21 '26 14:02

James Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!