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

dqx82308064 注册会员
2023-01-25 08:35

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.

didadoc 注册会员
2023-01-25 08:35

I used TryParse to check for null. Even if the parse fails Cell0 and Cell1 will be zero. I chose Integer but any numeric parse should work

    For a As Integer = 0 To dgv2.RowCount - 2
        Dim Cell0 As Integer
        Dim Cell1 As Integer
        Integer.TryParse(CStr(dgv2.Rows(a).Cells(0).Value), Cell0)
        Integer.TryParse(CStr(dgv2.Rows(a).Cells(1).Value), Cell1)
        dgv2.Rows(a).Cells(2).Value = Cell0 + Cell1

About the Author

Question Info

Publish Time
2023-01-25 08:35
Update Time
2023-01-25 08:35

Related Question


设计一个函数int stoi(char *str),将数字字符串str转换为一个整数




template <typename real, int dimension>


how to make gameobject transparent using slider in unity