【问题标题】:Input String was not in the correct format error c#输入字符串不是正确的格式错误c#
【发布时间】:2014-02-04 16:23:21
【问题描述】:

我正在将数据库中的值插入图表中。我正在从 2 列中提取数据, 第一列包含字符串值(字母、数字和空格的混合),第二列包含浮点值(只是数字类型)。 当我运行查询时,我不断收到此错误:“输入字符串格式不正确”有人可以帮我吗?

try { 
    Query = "SELECT * FROM Products;";
    Reader = conn.ExecuteStatement(Query);

    while (Reader.Read()) { 
        this.chart1.Series["Series1"].Points.
        AddXY((Double.Parse(Regex.Replace(Reader.GetString(1),@"[^\d|\.]",""))),
        (Convert.ToDouble(Reader.GetInt32(4))));
    }
}
catch (Exception ex) {
    MessageBox.Show(ex.Message); 
}

conn.CloseConnection();

【问题讨论】:

  • ex.Message 更改为 ex.ToString() 并向我们提供完整的例外情况。
  • 这里出现错误:System.formatException:Input string was not in a correct format.at System.Number.ParseSingle(String value, NumberStyles options, NumberFormationInfo numfmt) at System.Single.Parse(String s)
  • 您确定 SQL 查询返回的列顺序正确吗?
  • 解决方案适合你吗???
  • 是否需要传入正确的区域性来解析字符串,因为 Parse 使用当前区域性?如果您的本地文化对数据的小数有不同的要求,那么您可能需要传递不同的格式提供程序,例如CultureInfo.InvariantCulture

标签: c#


【解决方案1】:

这是一个数据问题。 Reader.GetString(1)Reader.GetString(4) 返回的内容无法解析或转换为 double

不要依赖SELECT * FROM Products,而是列出列名并确保从正确的列中进行选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多