【问题标题】:Add All the Values from a Column DataGridView从列 DataGridView 添加所有值
【发布时间】:2016-10-20 22:13:43
【问题描述】:

我正在使用 WinForms。如果价格列有“$”符号,如何添加它的值?当列不包含“$”符号时,我可以添加值,但是当它包含时,系统会引发错误。

这是我到目前为止所拥有的。这会将价格列中的所有值相加,如果它不包含“$”符号,则将其相加。

private void sum_Btn_Click(object sender, EventArgs e)
{
    Total_TxtBx.Text = (from DataGridViewRow row in dataGridView1.Rows
                        where row.Cells[2].FormattedValue.ToString() != string.Empty
                        select Convert.ToDecimal(row.Cells[2].FormattedValue)).Sum().ToString();
}

($1.00 + $2.00 + $3.00) 总文本框应等于 = $6.00

【问题讨论】:

  • 为什么不在第一个 where 之后添加这个:where !row.Cells[3]. FormattedValue. ToString(). Contains("$")
  • 那些$ 标志不应该是数据的一部分。该列的数据应为数字数据类型,但Format应包含$符号。

标签: c# .net winforms datagridview sum


【解决方案1】:

从这个问题Convert any currency string to double 可以看出,您需要使用不同的重载来解析您的值:

string x = "$3.00";
var result = decimal.Parse(x, NumberStyles.Currency);

// result = 3.00

在您的代码中:

private void sum_Btn_Click(object sender, EventArgs e)
{
    Total_TxtBx.Text = (from DataGridViewRow row in dataGridView1.Rows
                        where row.Cells[2].FormattedValue.ToString() != string.Empty
                        select decimal.Parse(row.Cells[2].FormattedValue, NumberStyles.Currency))
                       .Sum().ToString();
}

【讨论】:

  • 我正在尝试做其他事情。我试图总结价格行。但是因为每一列都有一个 $ 符号,所以系统会抛出一个错误。
  • 我不能使用这个,因为系统不允许我使用NumberStyles.Currency。我尝试了using System.Globalization,但随后row.Cells[2].FormattedValue 抛出错误。
  • 无法从“对象”转换为“字符串”
  • 我必须在Convert.ToString(row.Cells[2].FormattedValue) 中添加这一行,感谢您的帮助:)
  • @taji01 等等 :) 哈哈,而不是添加,然后你可以做 FormattedValue.ToString() 或者甚至更好 - 使用 .Value 而不是 FormattedValue (也许你甚至不需要使用parse的另一个重载)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 2012-03-08
  • 2021-12-13
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多