Argument 'Expression' cannot be converted to type 'DBNull' in vb.net

4.7k views Asked by At

I trying to check for DBNull value in my DataGridView on cellvaluechanged event.

Here's my code,

 Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    Try
        If IsDBNull(Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value()) Or _
              Val(Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) < 0 Then
         Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub



In my code i am trying to check that if that cell is empty or less than 0 than replace it with 0. But that doesn't seems to work and throws an exception Argument 'Expression' cannot be converted to type 'DBNull'. Any help will be appreciated.

1

There are 1 answers

2
matzone On BEST ANSWER

Try this ...

If IsDBNull(Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value()) Then
    Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0
Else 
    If Val(Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) < 0 Then
        Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0
    End If
End If