如何知道我的 Datagridview 中的所有单元格在 vb.net 中是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18631617/
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
How to know if all cells in my Datagridview are null in vb.net
提问by Matthew
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.
现在我想要的是我怎么知道我的所有单元格中是否有一个空值,只需单击一次按钮?例如,我有 5 列和 25 行。
Thank you
谢谢
回答by Matthew
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
回答by matzone
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
回答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
回答by Andrey Gordeev
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

