Freigeben über


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.

      NoteNote

      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.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Label1.Text="You clicked a button"
    End Sub
    
    public void Button1_Click (object sender, System.EventArgs e)
    {
       Label1.Text="You clicked a button.";
    }
    

    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.

    Private Sub Page_Load(ByVal Sender As System.Object, ByVal e _
        As System.EventArgs) Handles MyBase.Load
        If Not IsPostback Then
            ' This is called the first time the page has loaded.
            ' The user will not have been able to click any buttons yet.
        Else
            ' This is called if the form has been posted back, possibly
            ' by a button click.
            Me.Label1.Text = "You clicked a button."
        End If
    End Sub
    
    private void Page_Load(object sender, System.EventArgs e)
    {
       if (!IsPostBack)
       {
          // Evals true first time browser hits the page.
       }
       else
       {
          // This is called if the form has been posted back, possibly
          // by a button click.
          this.Label1.Text = "You clicked a button.";
       }
    }
    

    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.

    ' Set the CommandName property of the buttons to "Add", 
    ' "Subtract", "Multiply", and "Divide".
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       AddHandler Me.btnAdd.Click, AddressOf Calculate
       AddHandler Me.btnSubtract.Click, AddressOf Calculate
       AddHandler Me.btnMultiply.Click, AddressOf Calculate
       AddHandler Me.btnDivide.Click, AddressOf Calculate
    End Sub
    
    Public Sub Calculate(ByVal sender As Object, ByVal e As System.EventArgs)
       Dim op1 As Integer = CType(Me.TextBox1.Text, Integer)
       Dim op2 As Integer = CType(Me.TextBox2.Text, Integer)
       Dim result As Integer
       Select Case CType(sender, Button).CommandName
          Case "Add"
             result = op1 + op2
          Case "Subtract"
             result = op1 - op2
          Case "Multiply"
             result = op1 * op2
          Case "Divide"
             ' Divide two numbers and return an integer result.
             If op2 > 0 Then
                   result = op1 \ op2
             Else
                   result = 0
             End If
          Case Else
             ' Error handling code here.
       End Select
       Label1.Text = result.ToString()     
    End Sub
    
    // Set the CommandName property of the buttons to "Add", _
    // "Subtract", "Multiply", and "Divide".
    protected void Page_Load(object sender, 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 sender, System.EventArgs e)
    {
       int op1 = Convert.ToInt16(TextBox1.Text);
       int op2 = Convert.ToInt16(TextBox2.Text);
       int result = 0;
       switch(((Button)sender).CommandName)
       {
          case "Add" :
             result = op1 + op2;
             break;
          case "Subtract" :
             result = op1 - op2;
             break;
          case "Multiply" :
             result = op1 * op2;
             break;
          case "Divide" :
             // Integer division.
             if (op2 > 0) 
                   result = op1 / op2;
             else
                   result = 0;
             break;
          default:
             // Error handling code here.
             break;
       }
       Label1.Text = result.ToString();
    }
    

See Also

Reference

Button Web Server Controls Overview