VB.NET: listView find item (exact string)

Hi X-perts,

I need a fast code to find an item in ListView (without looping, if possible). I am using the following code now. The problem is that FindItemWithText always finds the 1st substring occurrence, but not the exact match.

any solutions that wouldn't imply looping throughout the listview items?

For Each f In rc.Fields
                        j = Me.ListView1.FindItemWithText(f.Name).Index
                        If (j <> -1) Then Me.ListView1.Items(j).Checked = True
                    Catch ex As Exception
                    End Try

Open in new window

Who is Participating?
HainKurtSr. System AnalystCommented:
sort it first, so it finds exact match first ;)
I'm pretty sure the .FindItemWithText method is looping, so there won't be a performance hit by looping manually to find the correct item.

For a simple ListView, I would likely loop thru the items collection by index. Something like:
Dim x as Integer
For x = 0 to Me.ListView1.Items.Count -1
  If Me.ListView1.Items(x).Text = f.Name
    Me.ListView1.Items(x).Checked = True
    Exit For
  End If

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.