Home > front end >  Sum DataGridView c#
Sum DataGridView c#

Time:06-07

I would like to show into a label the resul of the sum of all cells of one column. 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?

CodePudding user response:

You have to calculate sum first, then assign it to lbl_Subtotal.Text, something like

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,

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();

CodePudding user response:

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();

CodePudding user response:

u can add extension function for 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");
  • Related