From ListBox to TextBox

  • Thread starter Thread starter AnakinVB
  • Start date Start date
A

AnakinVB

Guest
Hello,
As you can see if you try out my code (below) I am able to populate a list box from whatever the user enters into a text box. However, I haven't quite gotten it to work in the reverse direction.

How can I populate a text box by single or double-clicking an item on a list box?
Here's what I've got so far:
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox2.Text = Cstr(ListBox1.Items())

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        ListBox1.Items().Add(TextBox1.Text)
    End Sub
Any .NET suggestions?
thx,
Anakin
 
Last edited by a moderator:
Visual Basic:
TextBox2.Text = CType(ListBox1.Items(ListBox1.SelectedIndex), String)

Using the vb tags helps people read your code by the way :)
 
Thanks divil

I will try to use the VB tags in this post. I'm guessing that I should use them like HTML tags. Feel free to show me the correct way if I get it wrong.

Anyway, now that I can populate my text box from my list box, I am trying to add in some error checking. If the list is empty, and you click on the listbox, my program crashes. I have made several different attempts to fix this. Now, I just get the message box no matter what.

**How can I fix this so that
a) the message box pops up only when the listbox is empty?
and
b) the text box populates when it is supposed to - i.e. the user has clicked on a list item?

Here is my latest .NET code:

Visual Basic:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items().Add(TextBox1.Text)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If ListBox1.SelectedIndex > Nothing Then
            TextBox2.Text = CType(ListBox1.Items(ListBox1.SelectedIndex), String)
        Else
            MsgBox("Items must be there to select them")
        End If

thx,
Anakin
 
Last edited by a moderator:
Use square brackets on the VB tags.

You can check if the .SelectedIndex property is -1 to see if there is nothing selected.
 
Thanks divil, that worked. For the sake of testing the vb tags, I'm going to paste my working code here:

Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items().Add(TextBox1.Text)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If ListBox1.SelectedIndex() = -1 Then
            MsgBox("Items must be there to select them")
        Else
            TextBox2.Text = CType(ListBox1.Items(ListBox1.SelectedIndex), String)
        End If

thx!
Anakin
 
Back
Top