【问题标题】:Sum datagridview value including decimal c#汇总 datagridview 值,包括十进制 c#
【发布时间】:2020-06-09 03:25:28
【问题描述】:

我怎样才能得到包括小数点在内的总和结果, 这是我尝试过的

// int sum;
decimal sum = 0;
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
    sum = sum + Convert.ToInt32(Convert.ToDouble(dataGridView1.Rows[row].Cells[6].Value));
    //sum1 = sum.ToString("N");
    //TotalAmount.Text = Math.Round(double.Parse(sum), 2).ToString();
}
//TotalAmount.Text = String.Format("{0:0.00}", sum);
TotalAmount.Text = Math.Round(sum,2).ToString();

【问题讨论】:

  • 你为什么使用Convert.ToInt32(Convert.ToDouble(dataGridView1.Rows[row].Cells[6].Value))?只需使用Convert.ToDecimal(dataGridView1.Rows[row].Cells[6].Value) 而不是Convert.ToInt32(Convert.ToDouble(dataGridView1.Rows[row].Cells[6].Value))
  • 如果您的DataGridView 的数据源绑定到DataTableDataSet,最好从底层数据源求和。检查这个question
  • 非常感谢您所做的更正.. 但我在 totalamount.text 而不是 123.12345 中得到相同的结果,它汇总为 1234.00,gridview 数据来自其他形式,而不是我的数据库作为数据源..
  • 那么我怀疑DataGrid中的数据是整数类型的。因此,您得到没有小数部分的整数值。尝试使用调试检查 DataGrid 中数据的类型。
  • 骗子,谢谢。。问题解决了,检查了整个代码过程,发现有if语句将结果重新转换为int reason to roundup..

标签: c# winforms


【解决方案1】:

如果您将数据源绑定到 datagridview,则尝试在数据源上对其求和,否则您也可以使用以下查询来获取总和

dataGridView1.Rows.OfType<DataGridViewRow>().Sum(x=>Convert.ToDecimal(x.Cells[6].Value));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2018-09-17
    • 2012-06-26
    • 2013-07-04
    相关资源
    最近更新 更多