[英]The Exception occured :- “The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.”
I want to store the DateTime data into the List .I have tried the below code but that throws the above exception. 我想将DateTime数据存储到List中。我尝试了下面的代码,但是抛出了上面的异常。 Please suggest some solution. 请提出一些解决方案。
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
List<DateTime> fdate = new List<DateTime>();
try
{
if (dr.HasRows)
{
while (dr.Read())
{
fdate.Add(Convert.ToDateTime(dr.ToString()));
}
}
}
catch (Exception)
{
throw;
}
It's been awhile since I worked with DataReaders but don't you have to specify the column name or index? 自从我使用DataReaders以来已经有一段时间了,但是您是否不必指定列名或索引? In your code you're trying to convert a DataReader to a DateTime object. 在您的代码中,您尝试将DataReader转换为DateTime对象。
fdate.Add(Convert.ToDateTime(dr.ToString()));
You need to specify the column in the DataReader to convert: 您需要在DataReader中指定要转换的列:
fdate.Add(Convert.ToDateTime(dr["column name"].ToString()));
And even then you're gonna need to check for nulls prior to doing the conversion. 即使这样,您仍需要在进行转换之前检查null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.