For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Column1").Value = ("CountMe") Then
count += 1
End If
Exit For
Next
Why do you have
Exit For
in there? That causes the loop to end after one
iteration. Remove it.
- Wayne
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello, I need to count how many rows got a specific text in Column1.
It looks like it works but the number is still 1, but there are more rows with this text. It looks like it doesn't count +1 for every row. How to do that?
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim count As Int32 = 0
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Column1").Value = ("CountMe") Then
count += 1
End If
Exit For
Next
CountLabel.Text = count
If (count > 0) Then
MessageBox.Show("Exist!")
Else
MessageBox.Show("Nothing here!")
End If
End Sub
Thanks.
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Column1").Value = ("CountMe") Then
count += 1
End If
Exit For
Next
Why do you have
Exit For
in there? That causes the loop to end after one
iteration. Remove it.
Maybe there is a space after CountMe, I would try this instead
If row.Cells("Column1").Value.ToString().Trim() = ("CountMe") Then
count += 1
End If
You can utilize a lambda statement to combine logic to get the count
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.Rows.Add(New Object() {"CountMe"})
DataGridView1.Rows.Add(New Object() {"CountMe"})
DataGridView1.Rows.Add(New Object() {"Other"})
DataGridView1.Rows.Add(New Object() {"CountMe"})
DataGridView1.Rows.Add(New Object() {"CountMe"})
DataGridView1.Rows.Add(New Object() {"CountMe"})
DataGridView1.Rows.Add(New Object() {"Other"})
End Sub
Private Sub CountButton_Click(sender As Object, e As EventArgs) Handles CountButton.Click
Dim count = DataGridView1.Rows.OfType(Of DataGridViewRow).
Count(Function(row) Not row.IsNewRow AndAlso CStr(row.Cells("Column1").Value) = "CountMe")
CountLabel.Text = count.ToString()
If (count > 0) Then
MessageBox.Show("Exist!")
Else
MessageBox.Show("Nothing here!")
End If
End Sub
End Class
Case insensitive
Private Sub CountButton_Click(sender As Object, e As EventArgs) Handles CountButton.Click
Dim valueToFind = "CountMe"
Dim count = DataGridView1.Rows.OfType(Of DataGridViewRow).
Count(Function(row) Not row.IsNewRow AndAlso
String.Compare(CStr(row.Cells("Column1").Value), valueToFind,
StringComparison.InvariantCultureIgnoreCase) = 0)
CountLabel.Text = count.ToString()
If (count > 0) Then
MessageBox.Show("Exist!")
Else
MessageBox.Show("Nothing here!")
End If
End Sub