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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19397048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:29:43  来源:igfitidea点击:

How to check if a datagridview cell is empty through button click in vb.net?

vb.netdatagridview

提问by J-J

I need help when filtering or checking if either one or more datagridview cell is null or not before saving the data. I have tried several codes but there is always an error. Below is the picture.

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

enter image description here

在此处输入图片说明

Thanks in advance.

提前致谢。

回答by Carlos Landeras

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

回答by Pierre-Olivier Pignon

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 :

或使用 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