简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM