Add column of DataGrid only with valid values

2

I'm using this function to add a column from my datagrid

public void Somatorio()
{
    decimal total = 0;
    foreach (DataGridViewRow row in dgv_inico.Rows)
    {
        total += Convert.ToDecimal(row.Cells["valor"].Value);
    }

    lbl_soma.Text = Convert.ToDouble(total).ToString("C");
}

The question is that there may be a column field of no value, there is an error, how do I add the column but only the fields that contain the value?

    
asked by anonymous 09.10.2017 / 16:03

3 answers

3

Modify your foreach to consider only rows containing the valor column that are not empty.

I'm using LINQ and C# 6 .

using System.Linq;

foreach (DataGridViewRow row in dgv_inico.Rows.Cast<DataGridViewRow>()
.Where(t => !string.IsNullOrEmpty(t.Cells["valor"].Value?.ToString())))
{
   total += Convert.ToDecimal(row.Cells["valor"].Value);
}

In this code I'm using sequential checking, that is, even if the column value is null, it does not give error.

    
09.10.2017 / 16:24
1

If the point is just not adding the ones that do not contain value, try this code:

public void Somatorio()
{
    decimal total = 0;
    foreach (DataGridViewRow row in dgv_inico.Rows)
    {
        if (!string.IsNullOrEmpty(Convert.ToString(row.Cells["valor"].Value))
            total += Convert.ToDecimal(row.Cells["valor"].Value);
    }

    lbl_soma.Text = Convert.ToDouble(total).ToString("C");
}

This will only count the columns where the value is not empty.

    
09.10.2017 / 16:07
1

Use linq, this will solve your problem:

using System.Linq;    

dgv_inico.AsEnumerable().Sum(c => c.Field<double>("valor"))
    
09.10.2017 / 18:49