Blaze M
Blaze M

Reputation: 200

Multiplying data in 2 datagridview columns

I have been looking around the internet for some useful guide, but I have found non - How can I multiple two numbers in row, remember that value and then do the same for the rest of rows in datagridview and all those values sum together. And the total summary display in textbox. Those two columns are displayed using SqlCommand . But I would like to change the value in textbox every time there is made change in column pocet datagridview (when I do change in datagridview it doesnt insert the values into SQL). So I didn't hesitate and I asked you in my previous question here and user varocarbas - I'm so thankful for his time which he spent making it.

He came up with this code:

 void calculateProductTwoColumns(int castkaIndex, int pocetIndex, int tot_rows)
    {
        try
        {
            double[] outVals = new double[tot_rows + 1]; 
            int curRow = 0;
            foreach (DataGridViewRow row in dtg_ksluzby.Rows)
            {
                curRow = curRow + 1;
                outVals[curRow] = (double)row.Cells[castkaIndex].Value * (double)row.Cells[pocetIndex].Value;

                kpriplac.Text = outVals.ToString();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex.Message.ToString());
        }


    }

So I tried to "improve" it to make it work like I desire but I think I little messed it up. I would like to multiply in each row columns pocet(dgv index 3) and cena(dgv index 2). So I call this method like this:

  calculateProductTwoColumns(2, 3, 4);

When I start debugging it says: Specified cast is not valid. I tried to debug it with breakpoints but I couldn't find where I make mistake.

pocet is int and castka is numeric numeric(15, 2)

Thank you so much for your time reading this, I will be pleased with any comentary or reference to guides.

Upvotes: 0

Views: 1109

Answers (1)

Romano Zumbé
Romano Zumbé

Reputation: 8079

Try to change your source like the following:

outVals[curRow] = Convert.ToDouble(row.Cells[castkaIndex].Value) * Convert.ToDouble(row.Cells[pocetIndex].Value);

Edit:

I would recommend something like this:

void calculateProductTwoColumns(int castkaIndex, int pocetIndex, int tot_rows)
    {
        try
        {
            double outVal = 0; 
            foreach (DataGridViewRow row in dtg_ksluzby.Rows)
            {
                outVal = outVal + Convert.ToDouble(row.Cells[castkaIndex].Value) * Convert.ToDouble(row.Cells[pocetIndex].Value);
            }

            kpriplac.Text = outVal.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex.Message.ToString());
        }


    }

Upvotes: 1

Related Questions