Search code examples
vb.netdatagridviewdbnull

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


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.


Solution

  • 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