Keypress warning use the new keyword if hiding was intended

I keep getting the following error message at void KeyPress(object sender, KeyPressEventArgs e):

Warning 'SpeedyRent.Form2.KeyPress(object, System.Windows.Forms.KeyPressEventArgs)' hides inherited member 'System.Windows.Forms.Control.KeyPress'. Use the new keyword if hiding was intended.

This is my code so far:

void KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

with the following 3 references:

this.totalTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);
this.remainTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);
this.paidTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);

What is causing it?

Jon Skeet
people
quotationmark

What is causing it?

You're declaring a method with the same name as an event declared in a base class. That hides the event within the derived class, which isn't a good idea in general.

Two options:

  • Use new as the compiler suggests
  • Just rename the method

Personally I'd take the latter approach, giving the method a name which actually says what it does:

private void SuppressNonDigits(object sender, KeyPressEventArgs e)
{
    ...
}

You can also subscribe using rather less verbose syntax than before, with method group conversions:

totalTxt.KeyPress += SuppressNonDigits;
remainTxt.KeyPress += SuppressNonDigits;
paidTxt.KeyPress += SuppressNonDigits;

people

See more on this question at Stackoverflow