共用方式為


How to: Respond to User Selection in a CheckBox Web Server Control

When the user selects a CheckBox control, the control raises an event that you can respond to.

Note

The CheckBoxList control raises events differently than individual CheckBox controls do. For details, see How to: Determine the Selection in List Web Server Controls.

You might not need to respond directly to the check event of a CheckBox control at all. You respond to the event only if it is important to know when the user has changed the check box selection. If you are interested only in the state of the check box when selected, and not whether it has changed, you can simply test the check box after the form has been posted to the server. For details, see How to: Get and Set a CheckBox Web Server Control Value Programmatically.

To respond to a selection in a CheckBox control

  • Create an event handler for the control's CheckedChanged event.

    By default, the CheckedChanged event does not immediately cause the page to be posted to the server. Instead, the event is raised in server code the next time the form is posted. To have the CheckedChanged event cause an immediate posting, set the CheckBox control's AutoPostBack property to true.

    Note

    The ability of a CheckBox control to post to the server when it is checked requires that the browser support ECMAScript (JavaScript) and that scripting be enabled on the user's browser.

    The following example displays "True" or "False" in a Label Web server control to reflect the latest change in a CheckBox control.

    Protected Sub CheckBox1_CheckedChanged(ByVal sender As _
       System.Object, ByVal e As System.EventArgs) Handles _
       CheckBox1.CheckedChanged
       Label1.Text = "CheckBox1 selection is: " & _
           CheckBox1.Checked.ToString()
    End Sub
    
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
       Label1.Text = "CheckBox1 selection is: " + CheckBox1.Checked.ToString();
    }
    

See Also

Reference

CheckBox and CheckBoxList Web Server Controls Overview