Freigeben über


How to: Respond to Changes in List Web Server Controls

The information in this topic applies to these list Web server controls: ListBox, DropDownList, CheckBoxList, and RadioButtonList.

When the user makes a selection in a list Web server control, the control raises an event that you can respond to directly. Normally, you do not need to respond directly to the selection event at all. Instead, it is more typical to test which item is selected after the form has been posted to the server by a control such as the Button control. For details about determining which item is selected, see Determining the Selection in a List Web Server Control.

To respond directly to changes in a list Web server control

  • Create an event handler for the control's SelectedIndexChanged event. By default, the SelectedIndexChanged 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 SelectedIndexChanged event cause an immediate posting, set the control's AutoPostBack property to true.

    NoteNote

    The event is raised as soon as the user makes a selection in the list control. If the AutoPostBack property is true, the form is posted with each selection, but the selected items are preserved with each round trip.

    The following code example shows how you can respond to a selection in a DropDownList control. The event handler displays the user's selection in a Label control.

    Security noteSecurity Note

    Controls in an ASP.NET page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. For more information, see How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender _
            As System.Object, ByVal e As System.EventArgs) _
            Handles DropDownList1.SelectedIndexChanged
       Label1.Text = "You selected " & DropDownList1.SelectedItem.Text
    End Sub
    
    Protected void DropDownList1_SelectedIndexChanged(object sender,
         System.EventArgs e)
    {
       Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
    }
    

See Also

Reference

CheckBox and CheckBoxList Web Server Controls Overview
DropDownList Web Server Control Overview
ListBox Web Server Control Overview
RadioButton and RadioButtonList Web Server Controls Overview

Concepts

BulletedList Web Server Control Overview