fast2021
fast2021

Reputation: 117

Transferring items from one listBox to another list

i have ListBox1 and ListBox2 and textbox

I want the following when setting a value in a TextBox. If the value in ListBox is1, then items are moved from the current value to the last items in not the first. to listbox2

enter image description here

Dim foo As String
Dim index As Integer = 0
Dim good As Integer = 0
foo = TextBox1.Text
ListBox2.Items.Clear()

For i = 0 To ListBox1.Items.Count - 1
    If ListBox1.Items(i).ToString = foo Then
        index = i
    End If
    If i >= index Then
        ListBox2.Items.Add(ListBox1.Items(good).ToString)
    End If
Next

Upvotes: 1

Views: 199

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460288

  1. As Lars has noted in a comment, the index is 0 at the beginning so the condition i >= index wil be always true. So you need to intialize it with Int32.MaxValue.

  2. You add always the first item, because good is always 0. You should use the loop variable i:

    ListBox2.Items.Add(ListBox1.Items(i).ToString())


Here is a LINQ version which simplifies the whole code, you don't need more:

ListBox2.Items.Clear()
Dim allAfter = ListBox1.Items.Cast(Of Object).SkipWhile(Function(item) Not TextBox1.Text.Equals(item))
ListBox2.Items.AddRange(allAfter.ToArray())

Upvotes: 1

Related Questions