I have a TextBox that a user can type a search term into and a ListBox that displays results. There is also a button will display some information based on the item selected on click.
I'm trying to scroll through the listbox using the up and down arrow keys so the user doesn't have to click the item, then the button. At that point I might as well just rely on the double click event to do the work since they are already on the item. However, I'm trying to make this more "keyboard only friendly".
The following code works, but with one minor flaw:
private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down && Results.SelectedIndex < (Results.Items.Count - 1))
{
Results.SelectedIndex++;
}
else if (e.KeyCode == Keys.Up && Results.SelectedIndex > 0)
{
Results.SelectedIndex--;
}
}
With this code, the cursor still moves left and right along with the selected item changing. I want it to remain where it is (not forcing it to the end). I didn't have any luck with the txtSearchTerm.Select(...) event, but I guess I could have missed something...
There is a TextChanged event, but it only calls to a search function I wrote that populates the list box as the user types, so I will leave that code out for simplicity.
Am I missing something or overlooking some method to make this TextBox/ListBox combo function how I'm intending?
Quick note: If you've ever used UltraEdit, I'm trying to mimic the behavior of that configuration window, basically.
You should use e.Handled = true; to cancel using the key that you processed:
private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
if (Results.SelectedIndex < (Results.Items.Count - 1))
Results.SelectedIndex++;
e.Handled = true;
}
else if (e.KeyCode == Keys.Up)
{
if (Results.SelectedIndex > 0)
Results.SelectedIndex--;
e.Handled = true;
}
}
I set e.Handled = true; if the key is Keys.Down or Keys.Up regardless of the SelectedIndex to completely disable moving caret using those keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With