Chrisetiquette Chrisetiquette - 1 month ago 10
Vb.net Question

Cannot figure out where to add IsDBNull vb.net

I keep getting this error:


Additional information: Operator '=' is not defined for type 'DBNull' and string


I've tried adding the IsDBNull Check to the code and cannot get it to work. Here is my code without my attmept at adding IsDBNull:

If EquationVariable = "=" Then
For Each R0w In Sorter.DataGridView1.Rows
Dim ColumnName As String = ListBox1.SelectedItem
Sorter.DataGridView1.CurrentCell = Sorter.DataGridView1.Item(ColumnName, R0w.index)
If Sorter.DataGridView1.CurrentCell.Value = SearchVariable Then
Sorter.DataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.Red
Else
End If
Next
Else
MsgBox(ListBox1.SelectedItem.ToString & " Doest not = " & SearchVariable)
End If


It is on this line that I am getting the error:

If PostalSorter.DataGridView1.CurrentCell.Value = SearchVariable Then


Here is how i tried to fix it:

If IsDBNull(PostalSorter.DataGridView1.CurrentCell.Value) Then
Else
If PostalSorter.DataGridView1.CurrentCell.Value = SearchVariable Then

PostalSorter.DataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.Red
Else

End If
End If

Answer

You can try the following:

If Not IsDBNull(Sorter.DataGridView1.CurrentCell.Value) AndAlso Sorter.DataGridView1.CurrentCell.Value = SearchVariable Then
      Sorter.DataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.Red

The AndAlso operator is handy in this instance because, unlike a regular And, if it comes across a condition that evaluates to false, it does not read any further. By making our first condition Not isDBNull and using an AndAlso, we ensure that the issue-causing comparison only occurs if in fact the CurrentCell.Value is not DBNull.