System.InvalidCastException:指定的强制转换无效

She*_*ady 2 c# sql-server datetime

我从数据库中检索了一个包含SQL Server中“时间”类型列的表,并尝试将其分配给DateTime变量,但出现此错误:System.InvalidCastException:指定的转换无效。

这是我的C#代码:

DateTime StartTime = (DateTime)dt.Rows[i]["startTime"];
Run Code Online (Sandbox Code Playgroud)

知道“ startTime”列的类型为“ time”,我可以在数据库中进行更改。有帮助吗?

小智 5

DateTime StartTime = Convert.ToDateTime(dt.Rows[i]["startTime"].ToString());
Run Code Online (Sandbox Code Playgroud)

如果您知道它可以为null。

DateTime StartTime = (dt.Rows[i]["startTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dt.Rows[i]["startTime"].ToString()));
Run Code Online (Sandbox Code Playgroud)