简体   繁体   中英

How to add items to listbox when a loop is involved?

Dim intX, intY As Integer
    intY = Nums.GetUpperBound(0)
    For intX = 0 To intY
        With Nums(intX)
            If .strFtID = strID Then

        ‘calls various subs/functions to get results to show in listbox

                listbox.Items.Add(String.Format(strFmt, "various titles”))
                listbox.Items.Add(String.Format(strFmt, variable results))
            End If
        End With
    Next

In this loop the listbox for titles is added for every match but I only want it to be added once. I also want to add “no match” if after the entire loop has searched and comes up with no match. There are multiple matches in this loop so it can't be placed within it or under “else”.

To be able to know if a match was found I usually add a boolean value outside the loop that I call "found". I then set it to false. If the if statement ever is a match i set found to true inside the if. This way when the loop ends I will know if there was a match or not.

Dim found as Boolean = false
For 
 If
  found = true
 End if
Next 

For the listbox I would do this:

If Not listbox.Items.Contains(String.Format(strFmt, "various titles”)) Then
 listbox.Items.Add(String.Format(strFmt, "various titles”))
End if

Try this code, I think this will suits your requirement.

Dim intX, intY As Integer
intY = Nums.GetUpperBound(0)
    For intX = 0 To intY
        With Nums(intX)
            If .strFtID = strID Then

               'This following If statement will restricts the duplicate entries, That is
               'multiple matches in your words.

               If Not listbox.Items.Contains(String.Format(strFmt, "various titles”)) Then
                listbox.Items.Add(String.Format(strFmt, "various titles”))
                listbox.Items.Add(String.Format(strFmt, variable results))
               End if

            End If
        End With
    Next

Now After the loop, just check the count of the listbox. If its count is greater than zero, then some matches had beed found in the upper loop. so that we can leave with out taking any further actions, Other wise just add the word "No Matches" in that listbox, refer the code below,

if listbox.Items.count > 0
 listbox.items.add(" NO MATCHES FOUND ")
end if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM