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
Next
CodePudding user response:
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:
dgv2.Rows(a).Cells(0).Value
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.
CodePudding user response:
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
Next