2

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
  • 5
    Check out this link. Looks like you need to use a time span. Commented May 8, 2012 at 20:15
  • Devin is right. In .NET, SQL Server 2008 time types map to TimeSpan objects. Commented May 8, 2012 at 20:23

2 Answers 2

5
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()));
Sign up to request clarification or add additional context in comments.

Comments

4

You should be able to cast it as a TimeSpan:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.