user6709318
user6709318

Reputation:

removing items in ComboBox when the similar item is selected Vb.net DesktopApp

i have two combo boxes like this

enter image description here

So for instance if i select Apple in the first Drop Box the second Drop Box shouldn't show the item Apple so i am wondering can this be done ? i am developing a Desktop application using VB.Net

Handles ComboBox1.DropDown
        With ComboBox1.Items
            .Add("Apple")
            .Add("Orange")
            .Add("Banana")

        End With

Upvotes: 1

Views: 2194

Answers (2)

Dan Rowe
Dan Rowe

Reputation: 151

Being that the items were added manually then perhaps there is a desire to not use a data source. If that is the case you could do something as simple as this:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.ComboBox1.Items.Add("Apple")
    Me.ComboBox1.Items.Add("Orange")
    Me.ComboBox1.Items.Add("Beer")
    Me.ComboBox2.Items.Add("Apple")
    Me.ComboBox2.Items.Add("Orange")
    Me.ComboBox2.Items.Add("Beer")
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    ' Just to see a visual of what was selected
    Dim selectedItem = CType(ComboBox1.SelectedItem, String)
    Dim resultIndex As Integer = ComboBox2.FindStringExact(ComboBox1.SelectedItem)
    Me.ComboBox2.Items.RemoveAt(resultIndex)
End Sub

End Class

The line that populates the selectedItem could be skipped all together I just put it in there to have a visual of what was selected. Then again you could store the items removed using the selectedItem variable which would give you the ability to revert any changes that were not desired.

One final thought is to remove the item from a command button.this way the item is not removed accidentally.

Upvotes: 0

FloatingKiwi
FloatingKiwi

Reputation: 4506

You could do it as follows:

    Public Class Form3

            Dim _items() As String = {"Apple", "Orange", "Banana"}

            Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
                    ComboBox2.DataSource = _items
                    ComboBox1.DataSource = _items
            End Sub

            Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
                    ComboBox2.DataSource = _items.Where(Function(item) item <> CStr(ComboBox1.SelectedItem)).ToList()
            End Sub

    End Class

On load we setup the datasources. Then when ComboBox1 has a new item selected we filter the list.

Upvotes: 3

Related Questions