Export (0) Print
Expand All

Responding to Changes in a List Web Server Control

Visual Studio .NET 2003

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

When the user makes a selection in 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 a 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 Web Forms page to be posted to the server. Instead, the event is raised in server code the next time the form is posted (as when a Button Web server control is clicked). To have the SelectedIndexChanged event cause an immediate posting, set the control's AutoPostBack property to true.

    Note   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 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 Note   Controls in a Web Forms 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 Scripting Exploits and Protecting Against Script Exploits in a Web Application.
    ' Visual Basic
    Private 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
    
    // C#
    private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
       Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
    }
    

See Also

ASP.NET Server Control Event Model | Creating Event Handlers in Web Forms Pages | ListBox Class

Show:
© 2015 Microsoft