繁体   English   中英

System.FormatException '输入字符串的格式不正确

[英]System.FormatException 'The format of the input string is incorrect

decimal Verbruikt = 0;
decimal res = 0;

// loop through the datagrid and sum the column 
foreach (DataGridViewRow item in dataGridView.Rows)
    if (item.Cells["Verbruikt"] != null
        && item.Cells["Verbruikt"].Value != null
        && item.Cells["Verbruikt"].Value != System.DBNull.Value)
       Verbruikt += Convert.ToDecimal(item.Cells["Verbruikt"].Value);

res = Convert.ToDecimal(Verbruikt);

我在这里做错了什么? 我在另一个项目中有这段代码没有任何问题。

DataGridViewCell.Value返回一个不透明的object 根据它的签名,它可以返回nullstringdecimalGuid ……它可以返回任何字面意思。 因此,您的问题归结为“如何将不透明object转换为decimal而不引发异常?”

此功能将帮助您做到这一点。

using System;
using System.Globalization;

static decimal? TryConvert(object? value, IFormatProvider? formatProvider)
{
    if (value is null)
        return null;
    if (value is decimal d)
        return d;
    if (value is string s && decimal.TryParse(s, NumberStyles.Any, formatProvider, out var parsed))
        return parsed;
    if (value is IConvertible convertible)
    {
        try
        {
            return convertible.ToDecimal(formatProvider);
        }
        catch
        {
            //
        }
    }
    return null;
}

然后你的代码可以这样写:

decimal res = 0;

// loop through the datagrid and sum the column 
foreach (DataGridViewRow item in dataGridView.Rows)
{
    var converted = TryConvert(item.Cells["Verbruikt"], CultureInfo.CurrentCulture);
    if (converted.HasValue)
       res += converted.Value;
}

请记住其他人在关于CultureInfo的评论中所说的话。 您可能不想要当前的文化,但可能想要CultureInfo.InvariantCulture CultureInfo的文档描述了差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM