-3

I am using the below code to get the sum of a column in a data grid view.

private void button16_Click(object sender, EventArgs e)
{
    int sum = 0;
    for (int i = 0; i < dataGridView4.Rows.Count; ++i)
    {
        sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
    }
    try
    {
        decimal tot = 0;
        for (int i=0; i <= dataGridView4.RowCount -1; i++)
        {
            tot += Convert.ToDecimal (dataGridView4.Rows[i].Cells[10].Value);
        }
        if (tot==0) {}
        textBox34.Text = tot.ToString();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

I am getting the error message

Input string was not in a correct format.

ِI found that the problem is in the formatting. Becasue the SQL server data type for that column is money. and the SQL server changes any number I save to this format. 00.0000 For example, If I save 10 SQL server saves it as 10.0000

If I remove the (.) I get no errors.

If I try to sum 10.0000 + 3.0000 it never works out.

Any ideas?

Logarr
  • 2,120
  • 1
  • 17
  • 29

1 Answers1

0

Your problem is that you're trying to convert a value with a decimal point from string to int. When using the money datatype in your DB, the best datatype to use in your code will be the decimal type. See the answer on What is the best data type to use for money in C#

So doing:

int val = Convert.ToInt32("10.00");

Will yield the following error (which is what you're receiving):

Unhandled Exception: System.FormatException: Input string was not in a correct format.

You can convert the value using the Convert.ToDecimal() method:

decimal val = Convert.ToDecimal("10.00");

If you want to remove the decimal portion of the value, you can use one of the following methods based on your requirements:

For example:

decimal val2 = Math.Round(val);

Or:

decimal val2 = Math.Truncate(val);

If you simply want to return the value as a string but without the decimal portion, you can do as follows:

decimal val = Convert.ToDecimal("10.00");
Console.WriteLine(val.ToString("0.#"));

Edit:

So in your code, change:

int sum = 0;

for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView4.Rows[i].Cells[10].Value);
}

For:

decimal sum = 0;

for (int i = 0; i < dataGridView4.Rows.Count; ++i)
{
    sum += Convert.ToDecimal(dataGridView4.Rows[i].Cells[10].Value);
}
M3talM0nk3y
  • 1,382
  • 14
  • 22