如何知道我的Datagridview中的所有单元格在vb.net中是否为null

时间:2013-09-05 08:40:47

标签: vb.net datagridview null

这是知道当前单元格是否为空的代码:

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

现在我想要的是如何知道我的所有单元格中是否只有一个单点击按钮?例如,我有一个5列和25行。

谢谢

4 个答案:

答案 0 :(得分:4)

最后,我制作了一个有效的代码,现在是:

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

答案 1 :(得分:1)

试试这个..

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

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

你可以写一个这样的函数:

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

或与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