在DataGridView中乘以两个单元格 - 如果单元格为空问题

时间:2013-09-12 11:24:54

标签: c# winforms datagridview

你好我有这个方法在datagridview的每一行中乘以两个单元格并对它们进行SUM运算。但问题是细胞是空的。我收到一个例外:

  

无法将对象从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;
                }

}

有办法申请吗?

提前谢谢

2 个答案:

答案 0 :(得分: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());
            }
        }

答案 1 :(得分: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());
    }


}