Check if a DataGridView is empty

14 Feb

Sometimes a DataGridView is used for user input and here is a simple way to check if the DataGridView is empty or not:

Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean
    Dim isEmpty As Boolean
    isEmpty = True
    For Each row As DataGridViewRow In dataGridView.Rows
        For Each cell As DataGridViewCell In row.Cells
            If Not String.IsNullOrEmpty(cell.Value) Then
                ' Check if the string only consists of spaces
                If Not String.IsNullOrEmpty(Trim(cell.Value.ToString())) Then
                    isEmpty = False
                    Exit For
                End If
            End If
    Return isEmpty
End Function

Please feel free to make any suggestion.


Posted by on February 14, 2012 in .NET, VB



4 responses to “Check if a DataGridView is empty

  1. joshuasue

    June 7, 2013 at 12:58 PM

    thanks begeeben! +100 😀

  2. Armen

    July 11, 2014 at 4:24 PM


    What if there is no data in datagrid view?
    In that case we can receive dbNull exception error “Invalid cast exception”.

    • Chidori

      December 15, 2014 at 3:51 AM

      if Yourdatagridview.rowcount = 0 then
      msgbox(“the data grid is empty”)
      end if

      • joseph320

        March 7, 2016 at 6:49 AM

        Thanks so much for this… It really help me


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: