Title: Perform multiple default actions in C#
Occasionally (but not often!) it's useful to let a form perform multiple default actions depending on the part of the form that the user is currently using. This example displays the message "Name updated" if you press Enter while updating the form's name fields. It displays the message "Address updated" if you press Enter while updating the form's address fields.
The program uses the following code to make this happen.
private void Name_Enter(object sender, EventArgs e)
{
AcceptButton = btnUpdateName;
}
private void Address_Enter(object sender, EventArgs e)
{
AcceptButton = btnUpdateAddress;
}
The first and last name text boxes and the top Update button all share the Enter event handler named Name_Enter. Similarly the address text boxes and the bottom Update button all share the Enter event handler named Address_Enter.
When focus moves to one of the controls, its Enter event handler updates the form's AcceptButton to the appropriate button. Then if the user presses Enter, that button fires.
Note that allowing a form to have multiple default actions is a fairly unusual technique so it may confuse users. To reduce confusion, you must it obvious that the form is divided into multiple sections. You also need to be certain that every control that can take the focus updates the form's AcceptButton property so the right default action is triggered.
Download the example to experiment with it and to see additional details.
|