O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.5. Displaying an Array as a Group of Checkboxes

Problem

You have data in an array that needs to be displayed as a group of checkboxes.

Solution

Use a CheckBoxList control and bind the array to it.

Add a CheckBoxList control to the .aspx file.

In the code-behind class for the page, bind the array to the CheckBoxList control.

Figure 1-4 shows the appearance of a typical CheckBoxList in a browser, with a couple of checkboxes preselected. Example 1-11 through Example 1-13 show the .aspx and code-behind files for an application that produces this result.

CheckBoxList with array data output

Figure 1-4. CheckBoxList with array data output

Discussion

The CheckBoxList control makes the job of generating a list of checkboxes extremely easy. Here’s a rundown of some of the attributes that control the checkbox display. In the example that we developed for this recipe, we have placed a CheckBoxList control in a Table cell to control its position on the form, as shown in Example 1-11.

The RepeatColumns attribute of the CheckBoxList control is used to set the number of columns in which the checkboxes are to be displayed.

The RepeatDirection attribute is set to Horizontal, which displays the checkboxes in rows from left-to-right and then top-to-bottom. This attribute can also be set to Vertical to display the checkboxes in columns from top-to-bottom and then left-to-right.

The RepeatLayout attribute is set to Table, which causes the CheckBoxList control to output an HTML table that contains the checkboxes. Using Table ensures the checkboxes are aligned vertically. This attribute can also be set to Flow, which causes the CheckBoxList control to output a <span> element for the checkboxes with <br> elements, thus placing the checkboxes in rows. In this case, unless all of your data is the same size, the checkboxes will not be aligned vertically.

The CssClass attribute controls the format of the text displayed with the checkboxes, and the width attribute sets the width of the HTML table that is generated.

Warning

The styles attribute can be used to format the data in any manner supported by inline HTML styles. If you’re considering using inline styles, though, it is important to remember that some older browsers do not fully support them.

Tip

If you need a list of radio buttons instead of checkboxes, substitute RadioButtonList for CheckBoxList in both the .aspx file and the code-behind.

The Page_Load method in the code-behind, shown in Example 1-12 (VB) and Example 1-13 (C#), builds the array of data by declaring an ArrayList and adding the text for the checkboxes to the ArrayList. It then sets the source of the data to the ArrayList and performs a data bind.

The ArrayList class provides a convenient, lightweight container for data that is to be bound to list controls. An ArrayList is virtually identical to the built-in Array type but adds automatic size management that makes it a bit easier to use.

To preselect a single checkbox, set the SelectedIndex property of the CheckBoxList control to the index of the item that is to be preselected. If multiple checkboxes need to be preselected, use the FindByText (or FindByValue) method of the Items collection in the CheckBoxList control to find the appropriate item(s), and then set the Selected property to True, as shown in the code-behind.

Example 1-11. CheckBoxList with array data (.aspx)

<%@ Page Language="vb" AutoEventWireup="false" 
         Codebehind="CH01CheckboxListWithArrayVB.aspx.vb" 
         Inherits="ASPNetCookbook.VBExamples.CH01CheckboxListWithArrayVB" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>Checkbox List With Array</title>
    <link rel="stylesheet" href="css/ASPNetCookbook.css">
  </head>
  <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">
    <form id="frmData" method="post" runat="server">
      <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td align="center">
            <img src="images/ASPNETCookbookHeading_blue.gif">
          </td>
        </tr>
        <tr>
          <td class="dividerLine">
            <img src="images/spacer.gif" height="6" border="0"></td>
        </tr>
      </table>
      <table width="90%" align="center" border="0">
        <tr>
          <td><img src="images/spacer.gif" height="10" border="0"></td>
        </tr>
        <tr>
          <td align="center" class="PageHeading">
            CheckBoxList With Array (VB)</td>
        </tr>
        <tr>
          <td><img src="images/spacer.gif" height="10" border="0"></td>
        </tr>
        <tr>
          <td align="center">
            <asp:CheckBoxList id="cbBooks" runat="server" 
                                                RepeatColumns="2" 
                                                RepeatDirection="Horizontal" 
                                                RepeatLayout="Table" 
                                                CssClass="MenuItem" 
                                                width="90%" />
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

Example 1-12. CheckBoxList with array data code-behind (.vb)

Option Explicit On 
Option Strict On
'-----------------------------------------------------------------------------
'
'   Module Name: CH01CheckboxListWithArrayVB.aspx.vb
'
'   Description: This class provides the code behind for
'                CH01CheckboxListWithArrayVB.aspx
'
'*****************************************************************************
Imports System.Collections

Namespace ASPNetCookbook.VBExamples
  Public Class CH01CheckboxListWithArrayVB
    Inherits System.Web.UI.Page

    'controls on form
    Protected cbBooks As System.Web.UI.WebControls.CheckBoxList

    '*************************************************************************
    '
    '   ROUTINE: Page_Load
    '
    '   DESCRIPTION: This routine provides the event handler for the page load
    '                event.  It is responsible for initializing the controls
    '                on the page.
    '
    '-------------------------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _
                Handles MyBase.Load
      Dim values As ArrayList


      If (Not Page.IsPostBack) Then
        'build array of data to bind to checkboxlist
                          values = New ArrayList
                          values.Add("Access Cookbook")
                          values.Add("Perl Cookbook")
                          values.Add("Java Cookbook")
                          values.Add("VB .Net Language in a Nutshell")
                          values.Add("Programming Visual Basic .Net")
                          values.Add("Programming C#")
                          values.Add(".Net Framework Essentials")
                          values.Add("COM and .Net Component Services")

                          'bind the data to the checkboxlist
                          cbBooks.DataSource = values
                          cbBooks.DataBind( )

                          'preselect several books
                          cbBooks.Items.FindByText("Programming C#").Selected = True
                          cbBooks.Items.FindByText(".Net Framework Essentials").Selected = True

      End If
    End Sub  'Page_Load
  End Class  'CH01CheckboxListWithArrayVB
End Namespace

Example 1-13. CheckBoxList with array data code-behind (.cs)

//----------------------------------------------------------------------------
//
//   Module Name: CH01DataGridWithXMLCS.aspx.cs
//
//   Description: This class provides the code behind for
//                CH01DataGridWithXMLCS.aspx
//
//****************************************************************************
using System;
using System.Collections;

namespace ASPNetCookbook.CSExamples
{
  public class CH01CheckboxListWithArrayCS : System.Web.UI.Page
  {
    // controls on form
    protected System.Web.UI.WebControls.CheckBoxList cbBooks;

    //************************************************************************
    //
    //   ROUTINE: Page_Load
    //
    //   DESCRIPTION: This routine provides the event handler for the page
    //                load event.  It is responsible for initializing the
    //                controls on the page.
    //
    //------------------------------------------------------------------------
    private void Page_Load(object sender, System.EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        ArrayList values = new ArrayList( );

                          // build array of data to bind to checkboxlist
                          values.Add("Access Cookbook");
                          values.Add("Perl Cookbook");
                          values.Add("Java Cookbook");
                          values.Add("VB .Net Language in a Nutshell");
                          values.Add("Programming Visual Basic .Net");
                          values.Add("Programming C#");
                          values.Add(".Net Framework Essentials");
                          values.Add("COM and .Net Component Services");

                          // bind the data to the checkboxlist
                          cbBooks.DataSource = values;
                          cbBooks.DataBind( );

                          // preselect several books
                          cbBooks.Items.FindByText("Programming C#").Selected = true;
                          cbBooks.Items.FindByText(".Net Framework Essentials").Selected = true;

      }
    }  // Page_Load
  }  // CH01CheckboxListWithArrayCS
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required