简体   繁体   English

涉及循环时如何将项目添加到列表框?

[英]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. 然后,我将其设置为false。 If the if statement ever is a match i set found to true inside the if. 如果if语句曾经匹配过,则在if内部将其设置为true。 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, 这样我们就可以不做任何进一步的操作了,否则,只需在该列表框中添加单词“ No Matches”,请参考下面的代码,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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