How to: Respond to Button Web Server Control Events
When a Button, LinkButton, or ImageButton Web server control is clicked, the current page is submitted to the server, where it is processed.
To respond to a button event
-
Create an event handler for one of the following events:
-
The page's Page_Load event. Because the button always posts the page to the server, this method will always run. Use the Page_Load event when it is not important which button was clicked, only that the form was submitted.
-
The button's Click event. Write an event handler for this event when it is important to know which button was clicked.
Note
If you are working with an ImageButton control and want to know the x and y coordinates of the user's click, you must create an event handler for this event. For details, see How to: Determine Coordinates in an ImageButton Web Server Control.
The following example shows how you can respond when a user clicks a Button Web server control. The method displays a message in a Label Web server control.
The following example shows how you can respond to a button click in a Page_Load event handler. The method tests the page's IsPostBack property to determine whether this is the first time the page has been processed or whether it was submitted by a button click.
The following example shows a simple four-function integer calculator. By binding all of the buttons (Add, Subtract, Multiply, and Divide) to the same method, you can handle all the calculations in one place and avoid repetitive code. Binding the buttons to the Calculate method is accomplished by using the AddHandler method in Visual Basic, and by using the += operator in C#. To ensure that the input values are integers, you could add error-handling code to the Calculate method or use the validation controls that are available for Web Forms.
-