5.6. Getting Multiple Choices from a ListBox

The ListBox control shows several items at a time inside a box. You set the number of visible items by using the Rows property. Users can select more than one item by holding down the Ctrl key while clicking the items. This example allows users to choose and display font names. Follow these steps to create the font list box:

  1. From the Toolbox, add a ListBox, Button, and Label control to the Web page.

  2. Select the ListBox and, in its Properties window (F4), set the SelectionMode property to Multiple.

  3. Double-click an empty area of Design view to create a handler for the Page Load event and add the following LINQ query to fill the ListBox with font names from a built-in .NET collection:

    If Not IsPostBack Then
     Dim q=From f In System.Drawing.FontFamily.Families _
     Select f.Name
     ListBox1.DataSource = q
     ListBox1.DataBind()
    End If

    For details on LINQ syntax, see Chapter 7 and this book's cheat sheet.

  4. Add the following Imports directive to the top of the page in Source view:

    <%@ Import Namespace="System.Linq" %>
  5. Return to Design view and double-click the Button control to create a Click event handler and add the following code:

    Dim strItems As String = ""
    For Each itm In ListBox1.Items
      If itm.Selected Then
        strItems = strItems & itm.Text & "<br />"
      End If
    Next
    Label1.Text = strItems

When you browse the page, the ListBox displays the server's fonts. Select ...

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.