如何通过vb.net中的按钮单击来检查datagridview单元格是否为空?

时间:2013-10-16 06:59:17

标签: vb.net datagridview

在保存数据之前过滤或检查一个或多个datagridview单元格是否为null时,我需要帮助。我尝试了几个代码,但始终存在错误。下面是图片。

enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:2)

For Each rw As DataGridViewRow In dataGridView1.Rows
    For i As Integer = 0 To rw.Cells.Count - 1                  
        If rw.Cells(i).Value Is Nothing OrElse rw.Cells(i).Value = DBNull.Value OrElse  String.IsNullOrWhitespace(rw.Cells(i).Value.ToString()) Then
                  'empty
        End If
    Next
Next

答案 1 :(得分: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