How can I change the selected text in a list box at runtime?

I've 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 looks like this:

enter image description here

I need to change this list text when the user enters a textbox. Is it possible to do this at runtime?

+3


source to share


2 answers


You are using the leave form 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 the item is actually selected in the ListBox:

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

      

+3


source


Instead of using a textbox, use the ListBox1_MouseDoubleClick

event

Private Sub ListBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDoubleClick

      

then add this code inside this event



Dim intIndex As Integer = ListBox1.Items.IndexOf(ListBox1.SelectedItem)
Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
    ListBox1.Items.Remove(ListBox1.SelectedItem)
    ListBox1.Items.Insert(intIndex, objInputBox)
End If

      

OR

Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
   ListBox1.Items(ListBox1.SelectedIndex) = objInputBox 
End If

      

+1


source







All Articles