The reason is that in the protected method
protected override void OnKeyPress(KeyPressEventArgs e)
{
MessageBox.Show((sender as TextBox).Text);
}
there is neither a
parameter
nor a
local variable
by name
sender
. Further there may not a
field
or
property
in the class with name
sender
. Hence, the above error.
In .NET the standard practice to implement events is to have a
protected method
like
OnEventName
. In this case the
Event
of
TextBox
is
KeyPress
and within the
TextBox
class this event is raised by calling the
OnKeyPress
event.
In .Net the standard pattern for events is of type
public void EventName(object sender, EventArgs e) { }
When a client subscribes to this event the
client
is to be informed who has raised this event so that they can use the
object
raising the event for some purpose.
When the
protected method
is used to raise the event it is already
present
in the concerned class and there is no need of sender. Hence, the
OnEventName
methods do not have
sender
parameter.