0

您好,我有这种方法可以将每行 datagridview 中的两个单元格相乘并将它们求和。但问题是当单元格为空时。我收到一个例外:

对象不能从 DBNUll 转换为其他类型

我想在此方法中添加一个条件,即如果 dtgksluzby 中的 castkaIndex2 或 pocetIndex2 不为空,则为它们执行此操作:

 private void calculateProductTwoColumns2(int castkaIndex2, int pocetIndex2, int tot_rows2)
    {
        try
        {
            double outVal = 0;
            foreach (DataGridViewRow row in dtg_ksluzby.Rows)
            {
                outVal = outVal + Convert.ToDouble(row.Cells[castkaIndex2].Value) * Convert.ToDouble(row.Cells[pocetIndex2].Value);
            }

            kpriplac.Text = outVal.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString());
        }


    }

很抱歉,我还没有尝试过任何事情,因为我不确定情况应该是什么样子。我在想这样的事情:

 for (int i = 0; i < (dtg_ksluzby.Rows.Count - 0); i++)
            {

                if (dtg_ksluzby.Rows[i].Cells["pocet"].Value == null ||
                   (string)dtg_ksluzby.Rows[i].Cells["pocet"].Value == string.Empty)
                {
                    dtg_ksluzby.Rows[i].Cells["pocet"].Value = 0;
                }

}

有没有办法应用这个?

先感谢您

4

2 回答 2

1

试试这个 :

    private void calculateProductTwoColumns2(int castkaIndex2, int pocetIndex2, int tot_rows2)
        {
            try
            {
                double outVal = 0;
                foreach (DataGridViewRow row in dtg_ksluzby.Rows)
                {
                   double cell1;
                   double cell2;
                   if(Double.TryParse(row.Cells[castkaIndex2].Value, out cell1) && Double.TryParse(row.Cells[pocetIndex2].Value, out cell2 ))
                   {
                    outVal = outVal + cell1 * cell2;
                   }
                }

                kpriplac.Text = outVal.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString());
            }
        }
于 2013-09-12T11:30:01.767 回答
1

System.DBNull.Value在执行以下操作之前,您应该检查单元格值是否存在Convert.ToDouble

private void calculateProductTwoColumns2(int castkaIndex2, int pocetIndex2, int tot_rows2)
{
    try
    {
        double outVal = 0;
        foreach (DataGridViewRow row in dtg_ksluzby.Rows)
        {
            outVal += Convert.ToDouble(row.Cells[castkaIndex2].Value is DBNull ? 0 : row.Cells[castkaIndex2].Value) * 
                      Convert.ToDouble(row.Cells[procetIndex2].Value is DBNull ? 0 : row.Cells[pocetIndex2].Value);
        }

        kpriplac.Text = outVal.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString());
    }


}
于 2013-09-12T11:36:59.123 回答