To be able to change properties and subscribe to events of controls inherited from your parent Form (or UserControl), the parent form should set those controls' Modifiers
property to protected
(or, in general, to any value such that fields generated for controls in parent form are visible to the child form). The default value for Modifiers
is private
.
When you create a form that inherits another form that contains different controls, there are not event handlers automatically hooked up for you. Instead you need to do that as in your code sample. Another approach is to attach that event handler in your base form, and then have the base form expose events that you can listen to. Example:
In the base form:
public event EventHandler ExecInvoked;
private void btnExec_Click(object sender, EventArgs e)
{
OnExecInvoked(e);
}
protected virtual void OnExecInvoked(EventArgs e)
{
EventHandler evt = ExecInvoked;
if (evt != null)
{
evt(this, e);
}
}
Then, in your inherited form, you can either set up an event handler for the ExecInvoked
event (you can probably do this using the events list in the property grid), or you can override the OnExecInvoked
method:
protected override void OnExecInvoked(EventArgs e)
{
base.OnExecInvoked(e);
// do what the form should do when Exec is invoked
}
This way you have encapsulated the internals of the base form, so that the child form does not know what kind of control that raises the event (it could even be several different controls leading to the same event being raised), but the base form still provides a clear point where the child form can react on it.