我想顯示一列所有單元格總和的label結果。我嘗試了我在網上看到的一個代碼,但該代碼不起作用。
這是代碼:
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();
}
有人可以幫助我嗎?
uj5u.com熱心網友回復:
您必須先計算總和,然后將其分配給 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();
讓我們嘗試一些 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();
uj5u.com熱心網友回復:
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();
uj5u.com熱心網友回復:
您可以為 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;
}
用法:
lbl_Subtotal.Text = dgv_Carrinho.getSumCell("COLUMN_NAME");
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489381.html
