Add Datagrid column with valid values only

Asked

Viewed 1,724 times

2

I’m using this function to add a column of 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 point is that there can be a field of the column without value, ai generates an error, as I do to add the column but only the fields that contain the value?

3 answers

3


Modify your foreach to consider only lines containing the column valor nonempty.

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 am using sequential checking, IE, even if the column value is null, no error.

1

If the point is just not to add those 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");
}

Thus only columns in which the value is not empty will be counted.

  • This is exactly what I need, but it generated an error Print of the http://pt-br.tinypic.com/r/2gx1hzs/9error

  • .Value is an object, and the function expects a string, just compare if Value is null

  • if (row.Cells["valor"].Value != null) puts that if, before the current if

  • 1

    I’ll edit the answer then.. to look more beautiful :P Convert.ToString() is cooler

1

Use Lynne, this will solve your problem:

using System.Linq;    

dgv_inico.AsEnumerable().Sum(c => c.Field<double>("valor"))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.