asp.net.ph

Skip Navigation Links

Responding to Button Control Events

Controls You Can Use on Web Forms   ASP.NET Standard Controls   Button Controls


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

  • Define an event-handling method for one of the following events:
    • The page’s Page_Load event. Because the button always posts the page to the server, this event method will always run. Use the Page_Load event when it’s not important which button was clicked, only that the form was submitted.
    • The button’s Click event. Write an event-handling method 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-handling method for this event. For details, see Determining Coordinates In an ImageButton Control.

The following example shows how you can respond when a user clicks a Button . Here, we simply display a message in a Label Control.

void myClickHandler ( object src, EventArgs e ) {
   myMessage.Text = "say something amusing here ... ";
}
  C# VB

The following example shows how you can respond to a button click in a Page_Load event-handling method. 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.

protected void Page_Load ( object src, EventArgs e ) {
   if ( !IsPostBack ) {
      // code here runs the first time browser hits the page.
   }
   else {
      // this takes over when the form has been posted back
   }
}
  C# VB

The following example shows a simple four-function integer calculator. By binding all 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 += operator in C#, and by using the AddHandler method in Visual Basic. To ensure that the input values are integers, you could add error handling code to the Calculate method or use the validation controls available for Web Forms.

protected void Page_Load ( object src, EventArgs e ) {
   btnAdd.Click += new System.EventHandler ( this.Calculate );
   btnSubtract.Click += new System.EventHandler ( this.Calculate );
   btnMultiply.Click += new System.EventHandler ( this.Calculate );
   btnDivide.Click += new System.EventHandler ( this.Calculate );
}

protected void Calculate ( object src, EventArgs e ) {
   ...
}
  C# VB
intcalc.aspx
Run Sample | View Source


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note