简体   繁体   English

如何使用快捷方式C#更改ComboBox的选定值

[英]How to change selected value of a ComboBox with a shortcut C#

First of all lets say that i am new to C#... I am using WinForms: I have tried using this code to change the value of the ComboBox with a shortcut. 首先,让我说我是C#的新手...我正在使用WinForms:我尝试使用此代码通过快捷方式更改ComboBox的值。 I have also tried using SelectedValue instead of SelectedIndex. 我也尝试过使用SelectedValue而不是SelectedIndex。 Afterwards I tried to focus the ComboBox before or after it changes value. 之后,我尝试在组合框更改值之前或之后关注组合框。 Finally i tried converting this to a stwitch statement, but every time i execute it nothing happens. 最终,我尝试将其转换为stwitch语句,但是每次执行时都没有任何反应。
I am using Visual Studio 2017 - when i tried to debug it, the debugger showed me that after it executes the code inside the if statement it goes inside the else statement and executes the code there again... 我正在使用Visual Studio 2017-当我尝试对其进行调试时,调试器向我展示了它在if语句内执行代码后将其放入else语句内并再次在该位置执行代码...

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.E)
    {
        //CBoxLimit.Focus();

        if (CBoxLimit.SelectedIndex == 0)
        {
            CBoxLimit.SelectedIndex = 1;
        }

        else
        {
            CBoxLimit.SelectedIndex = 0;
        }

        //CBoxLimit.Focus();
    }
}

Thanks in advance for your help... 在此先感谢您的帮助...

It seems that you should change the SelectedIndex on your instance of ComboBox and not on CBoxLimit . 看来你应该改变SelectedIndex您的实例ComboBox ,而不是CBoxLimit Also you should set the Form's KeyPreview property to True (see here ): 另外,您还应该将Form的KeyPreview属性设置为True (请参见此处 ):

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.E)
            {
                comboBox1.SelectedIndex = 1;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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