How to check if datagridview cell is Null

68,132

You need to check if the Value property of the DataGridViewCell is Nothing (the equivalent of null in C#).

You can do that with the following code:

If myDataGridView.CurrentCell.Value Is Nothing Then
    MessageBox.Show("Cell is empty")
Else
    MessageBox.Show("Cell contains a value")
End If


If you want to inform the user when they try to leave the cell that it has been left empty, you need to use similar code in the CellValidating event handler method. For example:

Private Sub myDataGridView_CellValidating(ByVal sender As Object,
               ByVal e As DataGridViewCellValidatingEventArgs)
               Handles myDataGridView.CellValidating
    If myDataGridView.Item(e.ColumnIndex, e.RowIndex).Value Is Nothing Then
        ' Show the user a message
        MessageBox.Show("You have left the cell empty")

        ' Fail validation (prevent them from leaving the cell)
        e.Cancel = True
    End If
End Sub
Share:
68,132
Furqan Sehgal
Author by

Furqan Sehgal

Hi, I am a programmer by hobby, at learning stage.

Updated on March 17, 2020

Comments

  • Furqan Sehgal
    Furqan Sehgal about 4 years

    I want to display a message if the value of cell of my datagridview is Null. Please advise how to do it. Thanks and best regards,

    Furqan

  • V4Vendetta
    V4Vendetta about 13 years
    recommend using e.FormattedValue while in CellValidating
  • stigzler
    stigzler over 8 years
    EDIT: This doesn't work. Use If String.IsNullOrEmpty(e.FormattedValue) Then instead.