0

I have a textbox in my form that I am using as a search bar for my listbox. Currently I have the textbox set up to actively select an item in the listbox while you type with the following code:

    private void TextBox1_TextChanged(object sender, EventArgs e) 
    {
        var textBox = (TextBox)sender;
        listBox1.SelectedIndex = textBox.TextLength == 0 ?
            -1 : listBox1.FindString(textBox.Text);
    }

What I would like to accomplish is to be able to also use the up & down arrow keys to adjust what is selected. For example if the listbox contains two items: Test1 & Test2 when you begin typing "t" test1 will be selected. Opposed to having to finish typing "test2" to change what is selected I would like to be able to type "t" then press the down arrow key to select test2 however keep the focus in the textbox.

I have tried using the following, however when pressing the up or down arrow key the cursor in the textbox adjusts instead of the selectedIndex

  private void TextBox1_KeyUp(object sender, KeyEventArgs e)
    {
        int index = listBox1.SelectedIndex;
        index = index--;
        listBox1.SelectedIndex = index;
    }
    private void TextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        int index = listBox1.SelectedIndex;
        index = index++;
        listBox1.SelectedIndex = index;
    }
  • Looks like a duplicate of this: https://stackoverflow.com/questions/28110999/handling-arrow-key-events-on-a-winform-textbox-without-overriding – felix-b Jul 07 '19 at 17:48

2 Answers2

1

You got confused by the event name.
KeyUp and KeyDown refers to pushing a keyboard button up and down, not pressing up and down arrows. To do what you are looking for, you would need either one of them, e.g: KeyUp like follows:

private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
    int index = listBox1.SelectedIndex;
    if(e.KeyCode == Keys.Up)
    {
         index--;
    }
    else if(e.KeyCode == Keys.Down)
    {
         index++;
    }
    listBox1.SelectedIndex = index;
}
Sohaib Jundi
  • 1,576
  • 2
  • 7
  • 15
0

@Sohaib Jundi THANK YOU!!! This cleared things up beyond belief! I ended up adjusting the code slightly to fix an error that was occurring, as well as a little bug the cursor was having in case anyone else runs into anything similar to this.

   private void TextBox1_KeyUp(object sender, KeyEventArgs e)
    {
        int index = listBox1.SelectedIndex;
        int indexErrorFix = listBox1.Items.Count;
        if (e.KeyCode == Keys.Up)
        {
            index--;

        }
        else if (e.KeyCode == Keys.Down)
        {
            index++;

        }
        if (index < indexErrorFix && index >= 0)
        {
            listBox1.SelectedIndex = index;
        }
        else { }

        textBox1.SelectionStart = textBox1.Text.Length;
    }