简体   繁体   English

发生异常:-“未将字符串识别为有效的DateTime。 从索引0开始有一个未知词。”

[英]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.

相关问题 该字符串未被识别为有效的DateTime。 从索引0开始有一个未知单词。 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0. label to string 如何解决此错误:System.FormatException:&#39;字符串未被识别为有效的DateTime。 从索引0开始有一个未知单词。 - how to solve this error: System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.' “System.FormatException:‘该字符串未被识别为有效的 DateTime。有一个从索引 0 开始的未知单词。” 在 C# - "System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0." in C# FormatException:该字符串未被识别为有效的DateTime。 从索引0开始有一个未知单词 - FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0 该字符串未被识别为有效的DateTime。 从索引26开始有一个未知词 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 26 字符串“未定义”未被识别为有效的日期时间。 有一个从索引“0”开始的未知单词 - The string 'undefined' was not recognized as a valid DateTime. There is an unknown word starting at index '0' 该字符串未被识别为有效的 DateTime。 从索引 0 开始有一个未知单词 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0 无法识别为有效的日期时间。 从索引0开始的未知单词 - Not Recognized as a valid datetime. Unknown word starting at index 0 该字符串未被识别为有效的DateTime,从索引25开始有一个未知单词 - The string was not recognized as a valid DateTime, There is an unknown word starting at index 25 无法将字符串识别为有效的DateTime。 引发异常 - String was not recognized as a valid DateTime. Throws an Exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM