1

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

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
taji01
  • 2,527
  • 8
  • 36
  • 80
  • Why not add this after the 1st where : `where !row.Cells[3]. FormattedValue. ToString(). Contains("$")` ? – TaW Oct 20 '16 at 22:51
  • Those `$` signs should not be part of data. The data of the column should be a number data type, but the `Format` should contain `$` sign. – Reza Aghaei Oct 21 '16 at 00:28

1 Answers1

1

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();
}
Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • I'm trying to do something else. I'm trying to sum up the price row. But because each column has a $ sign the system throws an error. – taji01 Oct 20 '16 at 22:20
  • I cant use this because, the system does not let me use `NumberStyles.Currency`. I tried `using System.Globalization`, but then `row.Cells[2].FormattedValue` throws an error. – taji01 Oct 20 '16 at 22:40
  • cannot convert from 'object' to 'string' – taji01 Oct 20 '16 at 22:42
  • i had to add this line in `Convert.ToString(row.Cells[2].FormattedValue)`, Thanks for the help :) – taji01 Oct 20 '16 at 22:43
  • 1
    @taji01 Wait :) haha instead of adding that then you can do `FormattedValue.ToString()` or maybe even better - use `.Value` instead of `FormattedValue` (maybe then you even don't need to use the other overload of `parse`) – Gilad Green Oct 20 '16 at 22:45