Click here to Skip to main content
15,915,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in form there is TextBox and a ListBox. When I Press Down or Up Key I want to Select ListBox item. Then After Selected item comes into the TextBox and Then after I want to select all Text in TextBox. But I couldn't do it.

Where must I change into the code ?

Advanced Thanks.

What I have tried:

VB
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       ListBox1.Items.Add("Times New Roman")
       ListBox1.Items.Add("Arial")
       ListBox1.Items.Add("Arial Narrow")
       ListBox1.Items.Add("Monotype corsiva")
       ListBox1.Items.Add("Verdana")
       ListBox1.Items.Add("Andelip")
       ListBox1.Items.Add("Obit BT")
       ListBox1.Items.Add("LCD")
       ListBox1.Items.Add("Western")
       ListBox1.Items.Add("Roman")

       ListBox1.SelectedIndex = 1
       TextBox1.Text = ListBox1.SelectedItem.ToString

   End Sub

   Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
       If e.KeyCode = Keys.Down Then
           If ListBox1.SelectedIndex <= ListBox1.Items.Count - 2 Then
               ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
               TextBox1.Text = ListBox1.SelectedItem.ToString

               ListBox1.Focus()
           End If
       End If

       If e.KeyCode = Keys.Up Then
           If ListBox1.SelectedIndex >= 1 Then
               ListBox1.SelectedIndex = ListBox1.SelectedIndex - 1
               TextBox1.Text = ListBox1.SelectedItem.ToString

               ListBox1.Focus()
           End If
       End If
   End Sub

   Private Sub ListBox1_GotFocus(sender As Object, e As EventArgs) Handles ListBox1.GotFocus
       TextBox1.SelectAll()
       TextBox1.Focus()
   End Sub
Posted
Updated 28-Jun-20 20:22pm

1 solution

Your TextBox isn't getting the keydown because the ListBox is an Input control, and can accept keys. So when you press the DOwn key, the system checks if it can be handled by teh List box, finds it can, so gets it to process it.

Add your code to the ListBox.KeyDown handler as well, and it'll work.
 
Share this answer
 
Comments
Nicomendox 29-Jun-20 4:21am    
You absolutely didn't understood yet what I want to do... I already get 100% correct answer here. hope not forbidden to share links.. maybe you like to learn too. God bless you.

Why can not select all text in textbox after focus to textbox ?-VBForums[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900