Matthew
Matthew

Reputation: 640

How to know if all cells in my Datagridview are null in vb.net

This is the code of knowing the current cell if it is null:

If dgv.CurrentCell.Value Is Nothing Then
    MsgBox("Cell is empty")
Else
    MsgBox("Cell contains a value")
End If

Now what I want is how can I know if there is a null in all of my cells in just a single buttong click? for example I have a columns of 5 and a rows of 25.

Thank you

Upvotes: 1

Views: 14611

Answers (4)

Pierre-Olivier Pignon
Pierre-Olivier Pignon

Reputation: 747

you can write a function like this :

Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean
    Dim isEmpty As Boolean = True
    For Each row As DataGridViewRow In dataGridView.Rows
        For Each cell As DataGridViewCell In row.Cells
            If Not String.IsNullOrEmpty(cell.Value) Then
                If Not String.IsNullOrEmpty(Trim(cell.Value.ToString())) Then
                    isEmpty = False
                    Exit For
                End If
             End If
        Next
    Next
    Return isEmpty
 End Function

or with Linq :

Public Function IsDataGridViewEmpty(ByRef dataGridView As DataGridView) As Boolean
    Dim isEmpty As Boolean = True
    For Each row As DataGridViewRow In From row1 As DataGridViewRow In dataGridView.Rows Where (From cell As DataGridViewCell In row1.Cells Where Not String.IsNullOrEmpty(cell.Value)).Any(Function(cell) Not String.IsNullOrEmpty(Trim(cell.Value.ToString())))
        isEmpty = False
    Next
    Return isEmpty
End Function

Upvotes: 0

matzone
matzone

Reputation: 5719

Try this ..

For y As Integer = 0 to dgv.Rows.Count - 1
  For x As Integer = 0 to dgv.ColumnCount - 1
    If IsDBNull(dgv.Rows(y).Cells(x).Value) Then
        MsgBox("Cell is empty")
    Else
        MsgBox("Cell contains a value")
    End If
  Next
Next

Upvotes: 1

Matthew
Matthew

Reputation: 640

Finally, I have made a working code and here it is:

For r = 0 To dgv.RowCount - 1
        If IsDBNull(dgv.Rows(r).Cells.Item(0).Value) _
      Or IsDBNull(dgv.Rows(r).Cells.Item(1).Value) _
      Or IsDBNull(dgv.Rows(r).Cells.Item(2).Value) _
      Or IsDBNull(dgv.Rows(r).Cells.Item(3).Value) _
      Or IsDBNull(dgv.Rows(r).Cells.Item(4).Value) _
      Then
            MsgBox("Blank fields are note allowed" + Environment.NewLine + "Please enter a number")
    Next

Upvotes: 5

Andrey Gordeev
Andrey Gordeev

Reputation: 32449

Try this:

For r As Integer = 0 To dgv.RowCount - 1
    Dim r As DataGridViewRow = dgv.Rows(r)
    For c As Integer = 0 To dgv.ColumnCount - 1 
        If dgv.Rows(r).Cells(c).Value Is Nothing Then
            MsgBox("Cell is empty")
        Else
            MsgBox("Cell contains a value")
        End If
    Next
Next

Upvotes: 0

Related Questions