taji01 taji01 - 1 month ago 8
C# Question

Add All the Values from a Column DataGridView

I'm using WinForms. How do you add the values of the Price column if it has a '$' sign? I am able to add the values when the column doesn't contain the "$" sign, but when it does the system throws an error.

This is what i have so far. This adds all the values from the price column and sums it up if it doesn't contain a '$' sign.

private void sum_Btn_Click(object sender, EventArgs e)
{
Total_TxtBx.Text = (from DataGridViewRow row in dataGridView1.Rows
where row.Cells[2].FormattedValue.ToString() != string.Empty
select Convert.ToDecimal(row.Cells[2].FormattedValue)).Sum().ToString();
}


($1.00 + $2.00 + $3.00)
Total TextBox should Equal = $6.00

enter image description here

Answer

As one can see from this question Convert any currency string to double you need to parse your value with a different overload:

string x = "$3.00";
var result = decimal.Parse(x, NumberStyles.Currency);

// result = 3.00

In your code:

private void sum_Btn_Click(object sender, EventArgs e)
{
    Total_TxtBx.Text = (from DataGridViewRow row in dataGridView1.Rows
                        where row.Cells[2].FormattedValue.ToString() != string.Empty
                        select decimal.Parse(row.Cells[2].FormattedValue, NumberStyles.Currency))
                       .Sum().ToString();
}