I have two combobox. I want to transfer all elements from combo1 to combo2 but with a filter only those item from combo1 will go to combo2 which are not in combo2.

For example

Combo1
________
This
Is
Help
But
Not

Combo2
_______
Is
But
And
Quick

So after clicking a button

Combo1
________
Is
But

Combo2
______
Is
But
And
Quick
This
Help
Not


Please help me......

Dani AI

Generated

OP wanted to move every item from one ComboBox to another but skip any that are already present. 's loop is a reasonable starting point (and yes, change the ListBox names to your ComboBox controls), but modifying a collection while iterating it can be error-prone and slow for larger lists. A safer pattern is to snapshot the items you intend to move, use a HashSet for fast existence checks, then add/remove using that snapshot.

Example (VB.NET):

' require Imports System.Linq
Dim destSet = New HashSet(Of String)(ComboBox2.Items.Cast(Of String)(), StringComparer.OrdinalIgnoreCase)
Dim toMove = ComboBox1.Items.Cast(Of String)().Where(Function(s) Not destSet.Contains(s)).ToList()

For Each item As String In toMove
    ComboBox2.Items.Add(item)
    ComboBox1.Items.Remove(item)
Next

Why this helps: the HashSet gives O(1) lookups instead of an inner loop, and ToList creates a safe snapshot so removing from ComboBox1 does not break the iteration. If your items are custom objects, cast to the actual type or compare a specific property (or supply a custom IEqualityComparer). If the ComboBoxes are data-bound, update the underlying list or binding source instead of manipulating Items directly. For details see the control and collection docs: ComboBox.Items, HashSet(Of T), and Enumerable.Cast.

Recommended Answers

All 6 Replies

Try this

Dim j As Integer = 0
        While j <= Me.ListBox1.Items.Count - 1


            Dim i As Integer = 0

            For i = 0 To Me.ListBox2.Items.Count - 1
                If Me.ListBox1.Items(j) = Me.ListBox2.Items.Item(i) Then
                    Exit For
                End If
            Next

            If i = Me.ListBox2.Items.Count Then
                Me.ListBox2.Items.Add(Me.ListBox1.Items.Item(j))
                Me.ListBox1.Items.RemoveAt(j)
            Else
                j += 1
            End If

        End While

What if i want to remove all items from combo1??

Just use ComboBox1.Items.Clear()

I see in your code that you use ListBox1 instead of ComboBox1

I replace that on my own and its working.. is that ok??

Oh sorry for that actually ListBox and ComboBox are like same...

Ok thank you .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.