Recommand · October 14, 2021 0

how to manipulation null value 'Operator '+' is not defined for type 'DBNull' and type 'DBNull'.'

For a As Integer = 0 To dgv2.RowCount - 2
    dgv2.Rows(a).Cells(2).Value = dgv2.Rows(a).Cells(0).Value + dgv2.Rows(a).Cells(1).Value

Assuming you want DBNull to be interpreted as 0 in your calculation, you can use an If() (kind of the VB version of the ternary conditional operator) to conditionally resolve to that value. So instead of this:


You would have something like this:

If(dgv2.Rows(a).Cells(0).Value = DBNull.Value, 0, dgv2.Rows(a).Cells(0).Value)

Which basically means "if the value from the database is null, use a zero, otherwise use the value from the database".

So the whole line might look like:

dgv2.Rows(a).Cells(2).Value = If(dgv2.Rows(a).Cells(0).Value = DBNull.Value, 0, dgv2.Rows(a).Cells(0).Value) + If(dgv2.Rows(a).Cells(1).Value = DBNull.Value, 0, dgv2.Rows(a).Cells(1).Value)

As an aside, since it’s clear that this makes the line of code much longer and more difficult to read, abstracting this behind any sort of helper function or extension method where possible would be a great next step.