Search code examples
c#eventskeypress

An error when trying to do key press event in C#


I add a key press event

private void listView_KeyPress(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        DeleteContact();
    }
}

The framework automatically creates the class for it:

this.listView.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress);

When compiling I get an error on System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress)

No overload for 'listView_KeyPress' matches delegate 'System.Windows.Forms.KeyPressEventHandler'    D:\...\MainForm.Designer.cs

I would appreciate any helpful answer, thanks.


Solution

  • The KeyPress event needs the parameter KeyPressEventArgs instead of KeyEventArgs.

    However the KeyPress event only gives you the character of the key you pressed. And the DELETE key has no character. Therefor you should use the event KeyDown instead, as this one is gives you the KeyCode instead:

    this.listView.KeyDown+= new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyDown);
    
    private void listView_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete)
        {
            DeleteContact();
        }
    }