将数据乘以2个datagridview列

时间:2013-07-20 14:58:12

标签: c# sql sql-server math datagridview

我一直在互联网上寻找一些有用的指南,但我找到了非 - 如何在行中多个两个数字,记住该值然后对datagridview中的其余行执行相同的操作以及所有这些值总和一起。总摘要显示在textbox中。使用SqlCommand显示这两列。但是,每当在textbox列数据视图中进行更改时,我想更改pocet中的值(当我在datagridview中进行更改时,它不会将值插入到SQL中)。所以我没有犹豫,我在上一个问题here和用户varocarbas中问过你 - 我非常感谢他花时间做这件事。

他想出了这段代码:

 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());
        }


    }

所以我试着“改进”它以使它像我想要的那样工作,但我想我有点搞砸了。我想在每行列中pocet(dgv索引3)和cena(dgv索引2)。所以我这样称呼这个方法:

  calculateProductTwoColumns(2, 3, 4);

当我开始调试时,它说:Specified cast is not valid.我试图用断点调试它,但我找不到我犯错的地方。

pocet是int,castka是数字数字(15,2)

非常感谢你花时间阅读本文,我会对任何评论或参考指南感到高兴。

1 个答案:

答案 0 :(得分:1)

尝试更改您的来源,如下所示:

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

编辑:

我会推荐这样的东西:

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());
        }


    }