Perform multiple default actions in C#

[multiple default actions]

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 Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in controls, user interface and tagged , , , , , , , , , , , , . Bookmark the permalink.

One Response to Perform multiple default actions in C#

  1. hazim says:

    very very good….

Leave a Reply

Your email address will not be published. Required fields are marked *