Hi have 2 list boxes on a form i have uploaded an example of the form im trying to code, would like to transfer an item to the next list box without duplicates so if you trying to send one item twice it should say msgbox("Borders already in the list box",information)"

8 Years
Discussion Span
Last Post by TomW

The listbox has a FindString and FindStringExact methods available to search the items.

intIndex = ListBox2.FindStringExact("YourSearchItem")
If intIndex >= 0 then msgbox("Item Already Exists")

Edited by TomW: n/a


Can you please go a little bit slow on this one
what is (intindex) because before i check if there no duplicates i haev to transfer: (item1) of (listbox1) to item1 of listbox2 then i will run the code for FindStringExact


If you look in the help file at the methods that I mentioned above, you will see that the ListBox.FindString & FindStringExact functions, will search the listbox for the string you provide. If the item is found within the list, it will return the index of that item in that listbox. If no items are found that match the search string it returns a -1 value.


As an example say I have two listbox's named (lstSource & lstTarget) and I want to transfer selected items from lstSource to lstTarget but first want to check that the item is not already in lstTarget:

Private Sub btnTransferItem_Click(...) Handles btnTransferItem.Click

        Dim intItemExists As Integer = -1
        Dim strTransferItem As String = ""

        'This can be done without the need of storing 
        'the selected/transfering item in a variable first. Using it
        'just for example purposes.

        strTransferItem = lstSource.Items(lstSource.SelectedIndex).ToString

        If lstTarget.FindStringExact(strTransferItem) = -1 Then
            'Item is not in the target listbox already
            'Item found and already exists in the target listbox
            MessageBox.Show(String.Format( _
                            "Item ""{0}"" is already in the target list box" _
                            , strTransferItem))
        End If

    End Sub
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.