计算Datagridview中的已填充行

时间:2016-08-23 15:56:43

标签: vb.net datagridview

我正在尝试通过函数计算datagridview中的已填充行 此函数包含2个参数,第一个是我想要填充的列数,第二个是datagridview的行数。
我试过这段代码:

Function dgvAggregate(ByVal colNum As Integer, ByVal dgvcount As Integer)
    Dim x As Integer = 0
    For i As Integer = 0 To dgvcount - 1
        For j As Integer = 0 To colNum
            If Not (dg.Rows(i).Cells(j).Value = Nothing) Then
                x += 1

            End If
        Next j
    Next i
    Return x
End Function  

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    MsgBox(dgvAggregate(2, dg.Rows.Count))
End Sub  

但是此代码返回具有值的单元格数! 如何根据用户输入的列数仅计算行数?

1 个答案:

答案 0 :(得分:2)

您正在为具有值的每个单元格递增 x 。您需要在 i 的循环中逐行测试和递增。

您需要在循环开始时设置一个标志,然后检查 nothing 的任何列,如果找到一些则更新标志。如果尚未更新标志,则递增 x

Function dgvAggregate(ByVal colNum As Integer, ByVal dgvcount As Integer)
    Dim x As Integer = 0
    Dim emptyColumns as Integer = 0

    For i As Integer = 0 To dgvcount - 1
        emptyColumns = 0
        For j As Integer = 0 To colNum
            If dg.Rows(j).Cells(i).Value = Nothing Then
                emptyColumns += 1
            End If
        Next j
        If emptyColumns = 0 Then
            x += 1
        End If
    Next i

    Return x
End Function  

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    MsgBox(dgvAggregate(2, dg.Rows.Count))
 End Sub