[英]Sum DataGridView c#
I would like to show into a label
the resul of the sum of all cells of one column.我想在
label
中显示一列所有单元格总和的结果。 I tried one code that I saw in the net but the code doesnt work.我尝试了我在网上看到的一个代码,但该代码不起作用。
Here's the code:这是代码:
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
{
lbl_Subtotal.Text += (Convert.ToDouble(row.Cells["Valor"].Value)).ToString();
}
Could someone help me?有人可以帮助我吗?
You have to calculate sum first, then assign it to lbl_Subtotal.Text
, something like您必须先计算总和,然后将其分配给
lbl_Subtotal.Text
,例如
var sum = 0;
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
sum += (Convert.ToDouble(row.Cells["Valor"].Value));
//Now assign it to label
lbl_Subtotal.Text = sum.ToString();
Lets try some linq operations,让我们尝试一些 linq 操作,
var sum = dgv_Carrinho.Rows.Cast<DataGridViewRow>()
.Select(double.TryParse(row.Cells["Valor"].Value?.ToString(), out double value) ? value : 0)
.Sum();
//Now assign it to label
lbl_Subtotal.Text = sum.ToString();
var count = 0;
foreach (DataGridViewRow row in dgv_Carrinho.Rows.Cast<DataGridViewRow>().Where(t => !string.IsNullOrEmpty(t.Cells["Valor"].Value?.ToString())))
{
count += (Convert.ToDouble(row.Cells["Valor"].Value)).ToString();
}
lbl_Subtotal.Text = count.ToSring();
u can add extension function for DataGridView您可以为 DataGridView 添加扩展功能
public double getSumCell(this DataGridView GridView, string ColName)
{
double sumValue = (from d in GridView.Rows
select d).Sum(DataGridViewRow x => Convert.ToDouble(x.Cells(ColName).Value));
return sumValue;
}
usage:用法:
lbl_Subtotal.Text = dgv_Carrinho.getSumCell("COLUMN_NAME");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.