Ayden
Ayden

Reputation: 45

Counting filled rows in Datagridview

I'm trying to count the filled rows in datagridview by a function.
This function contains 2 parameters, 1st one is the count of columns which i want to be filled and 2nd one the count of rows of datagridview.
I tried this code:

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  

But this code return the number of cells that has a value!
How can i count only rows depending on the columns count entered by user?

Upvotes: 0

Views: 1014

Answers (1)

cdkMoose
cdkMoose

Reputation: 1636

You are incrementing x for every cell which has a value. You need to be testing and incrementing on a row basis, in your loop over i.

You need to set a flag at the start of the loop and then check for any columns with nothing, updating the flag if you find some. If the flag hasn't been updated, then increment 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  

Upvotes: 2

Related Questions