vb.netwinformstextboxlistbox

How to change selected item text in list box at run time?


I tried with code like this:

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles MyBase.Leave
  ' This way is not working
  ListBox1.SelectedItem = TextBox1.Text
  ' This is not working too
  ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End Sub

The form is looked like this:

enter image description here

I need to change that list text while user typing in the text box. Is it possible to do that at run time?


Solution

  • You are using the form's leave event MyBase.Leave, so when it fires, it is useless to you.

    Try using the TextChanged event of the TextBox instead.

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
                                     Handles TextBox1.TextChanged
    

    Make sure to check if an item is actually selected in the ListBox:

    If ListBox1.SelectedIndex > -1 Then
      ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
    End If