简体   繁体   English

如何将“ x”个列表框项目分组并添加到另一个列表框?

[英]How to group “x” listbox items and add to another listbox?

I have to group, says 5 items of listbox1 and convert them to a string to add to listbox2. 我必须分组,说listbox1的5项并将它们转换为字符串以添加到listbox2。 Here is the code I have so far: 这是我到目前为止的代码:

dim s as string=""    'a string to collect listbox1 items 
dim count as integer=Listbox1.items.count

  Do While count > 0
        Select Case count

           Case Is <= 5
                For i = 0 To ListBox1.Items.Count - 1
                    s &= ListBox1.Items.Item(i).ToString
                    ListBox1.Items.RemoveAt(i)
                Next
                ListBox2.Items.Add(s)
                Exit Do 'If there are <=5 items, then done , exit loop

           Case Is > 5
                For i = 0 To 4
                    s &= ListBox1.Items.Item(i).ToString
                    ListBox1.Items.RemoveAt(i) 'delete each item in listbox1, after add
                Next
                ListBox2.Items.Add(s)
                s = "" ' Reset the s string to receive new items
                count = count - 5  'reduce count and loop over again
               End Select
Loop

Somehow, I could group almost the items in Listbox1 into groups of 5 and add to Listbox2, however there are some left in the listbox1 after the Loop (I see if I have 8 items then 3 is left). 不知何故,我可以将Listbox1中的几乎所有项目分组为5个组,然后添加到Listbox2中,但是在循环之后,listbox1中还有一些剩余(我看是否有8个项目,然后剩下3个)。 Could you guys show me where I was wrong in the code above? 你们能告诉我上面代码中哪里我错了吗?

Thank you very much ~ 非常感谢〜

I think your algorithm is too complicated, below is how i would approach it. 我认为您的算法过于复杂,下面是我的处理方法。

Hope this helps Graham 希望这对格雷厄姆有所帮助

    '
    ' Move items from ListBox1 to ListBox2
    '
    Dim s As String = ""
    For count As Integer = 0 To ListBox1.Items.Count - 1


        ' update every 5

        If (count Mod 5 = 0) Then

            ' Only update if not the first time
            If (count <> 0) Then
                ListBox2.Items.Add(s)
                s = ""
            End If
        End If
        s = s + ListBox1.Items.Item(count).ToString

    Next

    '
    ' Add the last ones
    '

    If (s <> "") Then
        ListBox2.Items.Add(s)
    End If

    '
    ' Clear down listbox 1
    '
    ListBox1.Items.Clear()

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

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