5.4. Checking CheckBox and CheckBoxList Controls

The CheckBox and CheckBoxList controls permit multiple choices. Unlike radio buttons, you can switch a check box on or off without affecting any of the other check boxes on the page.

5.4.1. Creating an arbitrary number of check boxes

The CheckBoxList control (like the RadioButtonList) is well suited to database applications where the number of items varies. In this section, you hook up (bind in geekspeak) a CheckBoxList to data.

To create a data-driven CheckBoxList, follow these steps:

  1. From the Toolbox, drop a CheckBoxList control, Button control, and Label control on a Web form.

  2. In the Properties window for the CheckBoxList control, set the RepeatColumns value to 2 and set the RepeatDirection value to Horizontal.

    These settings display the data in a two-column table.

  3. Double-click a blank area of the page to create a handler for the Page object's Load event and insert the following code:

    If Not IsPostBack Then
         Dim arrlGames As New ArrayList
         arrlGames.Add("Scrabble")
         arrlGames.Add("Crosswords")
         arrlGames.Add("WonderWord")
         arrlGames.Add("Sudoku")
         arrlGames.Sort()
         CheckBoxList1.DataSource = arrlGames
         CheckBoxList1.DataBind()
    End If

    The preceding adds items to a list, sorts the list, and tells the CheckBox to use the list for its data. Notice that the whole routine is wrapped in an If...End If sequence that tests the IsPostBack property. You want to fill the data only when the page first loads, not on each postback. Otherwise, you get ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.