Vb.net – ListBox and Item Values – Visual Basic 2010

listboxvb.netwinforms

I am writing a small application using VISUAL BASIC 2010 (It came packaged in Visual Studio 2010).

I have a list box set up to be populated by an Access database. The database has two columns: 1) Variable Name 2) Description.

As an example to be used in my question, here is a sample of my data:

Variable Name Description
DOG1 Dog Species that came from Family 1

Now, I have a list box that is populated by the Description column. This is what I need. I want to click a button and then depending on which item is clicked, display its corresponding "Description" in a textbox. This pertains to I believe DisplayMember and ValueMember. I've succeeded in doing this for one item at a time. My question is, how do I use a loop to do the same task for several items that might be selected in the list Box?

Here is my Code that works 100% for displaying items clicked one at a time.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TextBox1.Text = ListBox1.SelectedValue  
    End Sub

I thought that the following would work, but it doesn't and I'm not too sure why.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
        For i = 0 To ListBox1.SelectedValue - 1    
           TextBox1.Text = ListBox1.SelectedValue(i)
        Next i
End sub

Also, if it is possible, I'd like to take the items selected in listbox1 and display their values in another listbox. I've done this before with simple listboxes I've populated myself, but now that I'm working with value and display members, I can't seem to adapt the code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        For i = 0 To Listbox1.SelectedItems.Count - 1
            Listbox2.Items.Add(Listbox1.SelectedItems.Item(i))
        Next i

Thanks so much for the help in advance!

Best Answer

I think you need -

For i = 0 To ListBox1.SelectedValue - 1    
           TextBox1.Text &= ListBox1.SelectedValue(i)
        Next i

See the "&".

Haven't had a chance to double check yet.

Related Topic