Q:

Multiply two cells in DataGridView - if cell empty issue

Hello I have got this method that multiplies two cells in each row of datagridview and SUM them. But the issue is when the cell is empty. I receive an exception:

Object cannot be cast from DBNUll to other types

I would like to add to this method a condition that if the castkaIndex2 or pocetIndex2 in dtgksluzby is not empty then do this operation for them:  
 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());
        }

    }

I'm sorry that I haven't tried anything yet because I'm not sure how the condition should look like. 
I was thinkin about something like this:
 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;
                }

}

Is there way to apply this?
Thank you in advance

A:

You should check for the cell value if it's System.DBNull.Value or not before performing the 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());
    }

}

