[英]how to count the rows with blank cells in datagridview
我是vb.net 2008的用户,目前正在为我们部门开发系统。 我需要您的帮助,以对datagridview中具有空单元格的行进行计数。 行数必须显示在标签中。
这是我的代码。
For i = 0 To dgvMonitoringBoard.Rows.Count - 1
If dgvMonitoringBoard.Rows(i).Cells(24).Value.ToString = " " Then
x += 1
End If
Next
lblForTransfer.Text = "Items for transfer to Purchasing:" & x
下面的代码遍历DataGridView行和单元格。 如果在任何行上找到任何空单元格,则计数器将增加以对具有空单元格的行数进行计数。
Dim countRows as Integer = 0
For Each dgvRow As DataGridViewRow In dgvMonitoringBoard.Rows 'NOTE: Use dgvMonitoringBoard.Rows - 1 if AllowUserToAddRows property is set to True
For Each dgvCell As DataGridViewCell In dgvRow.Cells
If dgvCell.Value = "" Then
countRows += 1
Exit For
End If
Next
Next
lblForTransfer.Text = "Items for transfer to Purchasing: " + countRows.ToString
与@equisde略有不同。 我会为您的情况使用Linq
。 这将返回具有DBNull.Value
或空字符串的行数。
这是一个班轮...
Dim count As Integer = DataGridView1.Rows.Cast(Of DataGridViewRow).Where(Function(r) r.Cells.Cast(Of DataGridViewCell).ToList.Any(Function(c) c.Value Is DBNull.Value OrElse String.IsNullOrEmpty(CStr(c.Value).Trim))).Count
自上而下-有时更容易阅读...
Dim count As Integer = DataGridView1.Rows.Cast(Of DataGridViewRow) _
.Where(Function(r) r.Cells.Cast(Of DataGridViewCell).ToList _
.Any(Function(c) c.Value Is DBNull.Value _
OrElse String.IsNullOrEmpty(CStr(c.Value).Trim))).Count
那你就可以...
lblForTransfer.Text = "Items for transfer to Purchasing: " & count.ToString
注意:尽量不要将+
用于字符串连接,而将&
用于字符串连接。 您也可以将其放在函数中,然后将DataGridView
传递到该函数中,以便可以在需要的任何地方重复使用它并返回值。
按请求更新
这是我编写的共享函数,该函数采用DataGridView
对象和可选的列索引来进行搜索。 该函数可以在您想使用它的任何地方使用...注意:如果您有Allow Adding Rows
到True ,那么这也将排除新行,如果不允许的话,也没关系。
Public Shared Function EmptyCount(ByVal dgrid As DataGridView, Optional ByVal intColumn As Integer = -1) As Integer
Dim count As Integer = 0
If dgrid IsNot Nothing AndAlso dgrid.Rows.Count > 0 Then
If intColumn >= 0 Then 'Specific Column...
If intColumn <= dgrid.Columns.Count Then
count = dgrid.Rows.Cast(Of DataGridViewRow).Where(Function(rs) Not rs.IsNewRow) _
.Select(Function(r) r.Cells(intColumn)).Where(Function(r) r.Value Is DBNull.Value _
OrElse String.IsNullOrEmpty(CStr(r.Value))).Count
End If
Else 'Any columns...
count = dgrid.Rows.Cast(Of DataGridViewRow).Where(Function(rs) Not rs.IsNewRow) _
.Where(Function(r) r.Cells.Cast(Of DataGridViewCell).ToList _
.Any(Function(c) c.Value Is DBNull.Value _
OrElse String.IsNullOrEmpty(CStr(c.Value).Trim))).Count
End If
End If
Return count
End Function
使用范例
'Include all columns...
lblForTransfer.Text = "Items for transfer to Purchasing: " & EmptyCount(YOURDATAGRIDVIEWNAME).ToString
'Specific column...
lblForTransfer.Text = "Items for transfer to Purchasing: " & EmptyCount(YOURDATAGRIDVIEWNAME, 24).ToString
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.