sanjeewa
sanjeewa

Reputation: 45

Check the Datagridview is empty in vb.net

I want to check if a DataGridView is empty. If it is empty, then the window should be closed. I used this code, but it throws "NullReferenceException was unhandled". How should I fix it?

If DataGridViewReInfor.CurrentCell.Value Is Nothing Then
    Me.Close()
Else
    MessageBox.Show("Cell contains a value")
End If

Upvotes: 2

Views: 32628

Answers (3)

Jose Jesus
Jose Jesus

Reputation: 1

You can use DataGridView1.RowCount, but you have to be careful. You have to inactive users can add rows, before and after the check, with this, you are going to delete the rows it has editing.

Example.

DataGridView1.AllowUsersToAdd = false
If DataGridView1.Rows.Count = 0 Then
  MsgBox("You should add one row.")
  DataGridView1.AllowUserToAddRows = True
  Exit Sub
End If
DataGridView1.AllowUserToAddRows = True

Upvotes: 0

ehh
ehh

Reputation: 3480

DataGridView is like matrix containing Rows, Columns and Cells. A cell is represented by a specific row in a specific column.

The following, that you have done, is checking whenever a value in a specific cell is null:

If DataGridViewReInfor.CurrentCell.Value Is Nothing Then

Note: Before checking if the Value is Nothing, you need to check if the CurrentCell is Nothing. And this may be the reason you got the exception.

If DataGridViewReInfor.CurrentCell Is Nothing Then 

But if you purpose is to check whenever your DataGridView contains rows, you need to ask on the rowcount:

If DataGridViewReInfor.RowCount>0 Then

or Rows.Count

If DataGridViewReInfor.Rows.Count > 0 Then

Upvotes: 5

Joey
Joey

Reputation: 354526

You get the exception because either a variable or a property of an object you were accessing was Nothing. This is an exception that's trivial to find with a debugger (just hover over your expressions), in this case I'm fairly sure that CurrentCell is Nothing because there is no selection. This is the sort of thing that you should train yourself to check first because few of the common exceptions are actually surprising.

As for checking whether the DataGridView is empty: If there is no IsEmpty property you may have to look at other things. Maybe looking at RowCount and ColumnCount would help here.

Upvotes: 2

Related Questions