Overriding ComboBox to select item by pressing index through keyboard in C#
I want to override a combobox such that it can be selected by its position in the list by pressing key through keyboard.
Example:
ComboBoxMonths
- Jan
- Feb
开发者_StackOverflow社区- Mar
- Apr
- May
- Jun
. . .
When 'J' is pressed Jan is selected, and 'F' for 'Feb',....
I want to use it like this, when
1 is pressed then Jan ,
2 for Feb , etc.Is it possible ? If yes, How can I achieve that ?
This only works properly if the combo is set to DropDownList, which makes sense in your example. It also only covers 1-9. If you want to handle more than one digit, it requires more logic with timers.
public class MyComboBox : ComboBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
var index = e.KeyChar - '1';
if( index >= 0 && index < this.Items.Count )
this.SelectedIndex = index;
base.OnKeyPress(e);
}
}
精彩评论