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;
}