2
votes

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??

2
Check out this link. Looks like you need to use a time span.Devin
Devin is right. In .NET, SQL Server 2008 time types map to TimeSpan objects.Icemanind

2 Answers

5
votes
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()));
4
votes

You should be able to cast it as a TimeSpan:

var startTime = dt.Rows<TimeSpan>("startTime");