C# System.InvalidCastException:指定的强制转换无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10505797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.InvalidCastException: Specified cast is not valid
提问by Sherif ElNady
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.
我从数据库中检索了一个表,该表包含 sql server 中“时间”类型的列,我尝试将其分配给 DateTime 变量,但出现此错误:System.InvalidCastException: Specified cast is not valid。
here's my c# code:
这是我的 C# 代码:
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??
知道“startTime”列的类型为“time”,我可以在数据库中更改它。任何帮助?
采纳答案by Marcosvoda
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()));
回答by James Johnson
You should be able to cast it as a TimeSpan:
您应该能够将其转换为TimeSpan:
var startTime = dt.Rows<TimeSpan>("startTime");

