C# - Datagridview error occurs when column cell is empty

Asked

Viewed 63 times

0

I kindly ask that an experienced programmer help me resolve this error! In the presented code has a sum calculation, the problem occurs when I leave one of the cells in the dgviewPersonalized column 12 empty, occurring in the following error, "datagridview System.Invalidcastexception: 'Object cannot be converted from Dbnull to other types".

private void Frmtrimestre3_load(Object Sender, Eventargs and) { Dgvcalculo(); Personalizardgv(); }

    private void PersonalizarDGV()
    {

        // largura das colunas
        dgviewPersonalizado12.Columns[0].Width = 64;
        dgviewPersonalizado12.Columns[1].Width = 105;
        dgviewPersonalizado12.Columns[2].Width = 64;
        dgviewPersonalizado12.Columns[3].Width = 105;
        dgviewPersonalizado12.Columns[4].Width = 64;
        dgviewPersonalizado12.Columns[5].Width = 105;
        dgviewPersonalizado12.Columns[6].Width = 64;
        dgviewPersonalizado12.Columns[7].Width = 105;
        dgviewPersonalizado12.Columns[8].Width = 64;
        dgviewPersonalizado12.Columns[9].Width = 105;
        dgviewPersonalizado12.Columns[10].Width = 64;
        dgviewPersonalizado12.Columns[11].Width = 105;
        dgviewPersonalizado12.ColumnHeadersVisible = false;
    }

    private void DgvCalculo()
    {

        var dcalculo = dgviewPersonalizado12;
        

        dgviewPersonalizado12.AutoGenerateColumns = false;
        dgviewPersonalizado12.ColumnHeadersVisible = false;
        dgviewPersonalizado12.ColumnCount = 12;
        dgviewPersonalizado12.RowCount = 7;
        // Nome das colunas
        dcalculo.Columns[0].Name = "Data";
        dcalculo.Columns[1].Name = "Semana1";
        dcalculo.Columns[2].Name = "Data";
        dcalculo.Columns[3].Name = "Semana2";
        dcalculo.Columns[4].Name = "Data";
        dcalculo.Columns[5].Name = "Semana3";
        dcalculo.Columns[6].Name = "Data";
        dcalculo.Columns[7].Name = "Semana4";
        dcalculo.Columns[8].Name = "Data";
        dcalculo.Columns[9].Name = "Semana5";
        dcalculo.Columns[10].Name = "Data";
        dcalculo.Columns[11].Name = "Semana6";

        // data hora     
        dcalculo.Columns["Data"].ValueType = typeof(DateTime);
        dcalculo.Columns["Data"].DefaultCellStyle.Format = "dd/MMM";



        dcalculo.Columns["Semana1"].ValueType = typeof(decimal);
        dcalculo.Columns["Semana1"].DefaultCellStyle.Format = "c";

        decimal total2 = 0;
        
        
            foreach (DataGridViewRow row in dcalculo.Rows)
            {
                total2 += Convert.ToDecimal(row.Cells["Semana1"].Value);
            }

            label20.Text = total2.ToString("c");
      
    }

   private void dgviewPersonalizado12_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        DgvCalculo();           
    }

1 answer

0


Need to validate if the value is null before adding, mainly because it is converting, which generates a Exception by being null.

You can for example put a if before adding up:

if (row.Cells["Semana1"] != null && row.Cells["Semana1"].Value !=  DBNull.Value)
{
    total2 += Convert.ToDecimal(row.Cells["Semana1"].Value);
}

Or if you want to leave the code outside the if, if null, continue to the next line:

if (row.Cells["Semana1"] == null || row.Cells["Semana1"].Value ==  DBNull.Value)
{
    continue;
}

total2 += Convert.ToDecimal(row.Cells["Semana1"].Value);
  • The code says that the name " Row " does not exist in the current context. It has how to solve this detail?

  • You’re doing it inside the foreach?

  • I put inside the foreach, the "Row" no longer gives error the code runs, but the error message "datagridview System.Invalidcastexception: 'Object cannot be converted from Dbnull into other types" unfortunately continues.

  • may need to validate the value tbm, updated the response

  • yes @natanfernandes, inside the foreach

  • Thank you very much, God bless you all, I did!!! No more error, but I made this small change that along with yours solved the problem.

  • 1

    The change was the following I switched " null " by " Dbnull.Value " and it worked perfectly.

  • good @Marciovalerio, you’re right, I’ll update on the question :)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.