C#中的组合框上的KeyPress事件

时间:2015-01-04 11:06:18

标签: c# combobox windows-forms-designer

我在桌面应用程序中有一个组合框,我试图给它一个KeyPress动作监听器

这是我的代码

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int selectedIndex = combobox.SelectedIndex;
                if (selectedIndex >= 0)
                {
                    switch (selectedIndex)
                    {
                        //.......
                    };
                    this.Close();
                }
            }
        }

现在我需要将它添加到组合框中,我尝试类似

this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);

但它不起作用。

4 个答案:

答案 0 :(得分:3)

您需要为事件添加处理程序,而不是某些参数。 (它甚至可以编译吗?)

而不是

this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);

this.combobox.KeyDown += new KeyEventHandler(this.comboBox1_KeyDown);

KeyEventHandler位于System.Windows.Forms命名空间中。

答案 1 :(得分:0)

private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.KeyDown += comboBox1_KeyDown;
    }

答案 2 :(得分:0)

除了编译问题,我认为你应该使用SelectedIndexChanged处理SelectedIndex 事件,因为KeyDown 如果在SelectedIndex更改之前触发。

comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

答案 3 :(得分:0)

您的代码存在问题,请connecting between The Event Handler Method and The Event

this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);

在上面的代码行中,您使用KeyEventArgs作为事件处理程序方法。但它不是事件处理程序方法。

相反,您应该使用KeyEventHandler,这是处理事件的相应事件处理程序方法。

EventArgs

EventArgs表示包含事件数据的类的基类,并提供用于不包含事件数据的事件的值。

事件处理程序方法使用包含事件数据的EventArgs实例来根据需要执行操作。

<强> KeyEventHandler

KeyEventHandler是处理控件的KeyUpKeyDown事件的方法。

类似于KeyPress事件,有KeyPressEventHandler方法。

因此,您应该将代码更改为:

this.comboBox.KeyDown += 
                  new System.Windows.Forms.KeyEventHandler(this.ComboBox_KeyDown); 
相关问题