The <asp:CheckBoxList> control creates a group of checkboxes rather than a single checkbox. It works very much like the <asp:RadioButtonList> control. Checkboxes can be created with scripts and they can be bound to data sources. The following set of checkboxes is created by extracting BookType field values from the BooksDB.mdb database and automatically producing a checkbox for each value.
Format for CheckBoxList Control
Unlike the <asp:CheckBox> control, which creates a single checkbox, the <asp:CheckBoxList> control creates a group of checkboxes. They can be created manually or by script, or the control can be bound to a data source as in the previous example. The general format for the CheckBoxList control is shown below.
<asp:CheckBoxList id="id" Runat="Server" AutoPostBack="True|False" CellPadding="n" CellSpacing="n" DataSourceID="id" DataTextField="field" DataTextFormatString="{string}" DataValueField="field" RepeatColumns="n" RepeatDirection="Horizontal|Vertical" RepeatLayout="Flow|Table" TextAlign="Left|Right" property="value"... OnSelectedIndexChanged="subprogram" > <asp:ListItem Selected="False|True" Text="string" Value="value" /> ... </asp:CheckBoxList>
The control contains one or more <asp:ListItem> controls, each representing a checkbox in the set. The default layout is shown in the following example with preselected boxes.
<asp:CheckBoxList id="CheckList" Runat="Server"> <asp:ListItem Text="Red" Value="#FF0000" Selected="True"/> <asp:ListItem Text="Green" Value="#00FF00"/> <asp:ListItem Text="Blue" Value="#0000FF" Selected="True"/> </asp:CheckBoxList>
The Text property gives the checkbox's label, the Value property sets the value of the checkbox, and the Selected="True" property prechecks the checkbox. The TextAlign property displays labels to the right (default) or left of the checkboxes.
When the CheckBoxList control is rendered in XHTML, the checkboxes are formatted inside a table to control their alignment. The CellPadding and CellSpacing properties give the number of pixels surrounding checkboxes and between table cells to separate or compact their arrangement. To format checkboxes outside of a table arrangement, set the RepeatLayout="Flow" property.
When a list contains a large number of checkboxes, they can be displayed in multiple columns. The RepeatColumns property is set to the number of columns and RepeatDirection lists the checkboxes vertically (default) or horizontally. Below is a list of nine checkboxes for which RepeatColumns="3" and RepeatDirection="Horizontal" are specified. CellSpacing is set at 5 pixels to increase spacing between the boxes.
<asp:CheckBoxList id="CheckList" Runat="Server" RepeatColumns="3" RepeatDirection="Horizontal" CellSpacing="5"> <asp:ListItem Text="CheckBox 1"/> <asp:ListItem Text="CheckBox 2"/> <asp:ListItem Text="CheckBox 3"/> <asp:ListItem Text="CheckBox 4"/> <asp:ListItem Text="CheckBox 5"/> <asp:ListItem Text="CheckBox 6"/> <asp:ListItem Text="CheckBox 7"/> <asp:ListItem Text="CheckBox 8"/> <asp:ListItem Text="CheckBox 9"/> </asp:CheckBoxList>
Determining CheckBox Properties
More than one of the checkboxes can be checked to make multiple selections. Therefore, all of the checkboxes in the list need to be evaluated to see which ones are checked. Like RadioButtonLists, CheckBoxLists have an Items collection representing the set of checkboxes in a list. A For Each...Next loop can be set up to iterate the items to discover those whose Selected property is "True". Those particular checkboxes have Text and Value properties that can be extracted.
<SCRIPT Runat="Server"> Sub Get_CheckBoxes (Src As Object, Args As EventArgs) Dim Item As ListItem For Each Item in CheckList.Items If Item.Selected = True Then ItemText.Text &= Item.Text & " " ItemValue.Text &= Item.Value & " " End If Next End Sub </SCRIPT> <form Runat="Server"> <asp:CheckBoxList id="CheckList" Runat="Server" RepeatDirection="Horizontal"> <asp:ListItem Text="Red" Value="R"/> <asp:ListItem Text="Green" Value="G"/> <asp:ListItem Text="Blue" Value="B"/> </asp:CheckBoxList><br/> <asp:Button Text="Select" OnClick="Get_CheckBoxes" Runat="Server"/><br/> Item.Text: <asp:Label id="ItemText" EnableViewState="False" Runat="Server"/> Item.Value: <asp:Label id="ItemValue" EnableViewState="False" Runat="Server"/> </form>
As in the case of the <asp:CheckBox> control, the checkboxes themselves can trigger a subprogram call by coding AutoPostBack="True"; the OnSelectedIndexChanged event handler names the subprogram. This technique is not likely to be used in order to permit selection of more than one checkbox prior to running the subprogram.
Scripting the CheckBoxList
One of the advantages of using a CheckBoxList over a CheckBox control is that items can be added to a list programmatically. The method is the same as for a RadioButtonList. Script commands pertinent to creating checkboxes for a CheckBoxList are shown below.
Dim NewItem As ListItem NewItem = New ListItem("text","value") CheckBoxList.Items.Add(NewItem) or CheckBoxList.Items.Add(New ListItem("text","value")) CheckBoxList.Items.Insert(index, New ListItem("text","value")) CheckBoxList.Items.RemoveAt(index) CheckBoxList.Items.Clear() CheckBoxList.Items.Count
The following example defines a CheckBoxList with individual checkboxes added by a script when the page is loaded.
<SCRIPT Runat="Server"> Sub Page_Load If Not Page.IsPostBack Then CheckList.Items.Add(New ListItem("Red","R")) CheckList.Items.Add(New ListItem("Green","G")) CheckList.Items.Add(New ListItem("Blue","B")) End If End Sub </SCRIPT> <form Runat="Server"> <asp:CheckBoxList id="CheckList" Runat="Server"/> </form>
The CheckBoxList's Items collection is built through the collection's Add() method. New ListItem entries are added to the collection and both Text and Value properties are specified. If a single value is specified in the list, it is treated as both the Text and Value properties of the checkbox.
The Items collection also supports Insert() , RemoveAt(), and Clear() methods similar to their use for a RadioButtonList control. The Items.Count property gives the number of checkboxes in a list.
Binding to a Data Source
Text and Value properties for a CheckBoxList can be automatically assigned, or bound, from an external data source, normally a database table. The following list is created by binding the BookType field of the BooksDB.mdb database to an AccessDataSource, and assigning these values to the Text and Value properties of the checkboxes. Selected checkboxes display those book types in a GridView table.
<SCRIPT Runat="Server"> Sub Preselect_Checkbox (Src As Object, Args As EventArgs) BookList.Items(0).Selected = True End Sub Sub Get_Book_Type (Src As Object, Args As EventArgs) '-- Determine if any boxes are checked Dim FoundChecked = False Dim Item As ListItem For Each Item In BookList.Items If Item.Selected Then FoundChecked = True Exit For End If Next '-- If boxes are checked, build an SQL statement If FoundChecked = True Then Dim SQLString As String SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty " & _ "FROM Books WHERE " For Each Item in BookList.Items If Item.Selected Then SQLString &= " BookType = '" & Item.Value & "' OR " End If Next SQLString = Left(SQLString, Len(SQLString) - 4) SQLString &= " ORDER BY BookID" BookSource2.SelectCommand = SQLString '-- Otherwise, check the first checkbox Else BookList.Items(0).Selected = True End If End Sub </SCRIPT> <form Runat="Server"> <h3>View Book Types</h3> <asp:AccessDataSource id="BookSource1" Runat="Server" DataFile="../Databases/BooksDB.mdb" SelectCommand="SELECT DISTINCT BookType FROM Books ORDER BY BookType"/> <asp:CheckBoxList id="BookList" Runat="Server" RepeatColumns="3" RepeatDirection="Vertical" DataSourceID="BookSource1" DataTextField="BookType" DataValueField="BookType" Style="float:left" OnDataBound="Preselect_Checkbox"/> <asp:Button Text="Select Types" OnClick="Get_Book_Type" Runat="Server"/> <br clear="left"/><br/> <asp:AccessDataSource id="BookSource2" Runat="Server" DataFile="../Databases/BooksDB.mdb" SelectCommand="SELECT BookID, BookTitle, BookPrice, BookQty FROM Books WHERE BookType = 'Database' ORDER BY BookID"/> <asp:GridView id="BookGrid" DataSourceID="BookSource2" Runat="Server" EnableViewState="False"/> </form>
No scripting is required to create the CheckBoxList. It is produced automatically by associating an AccessDataSource with the CheckBoxList control. The AccessDataSource issues an SQL statement to return a recordset of BookType values from the Books table. Since duplicate BookType values appear in the records, only single instances of unique (DISTINCT) values are returned. This recordset is bound to the CheckBoxList through the latter's DataSourceID property, naming the id of the AccessDataSource. A checkbox is created for each returned record. The BookType value is used for both the Text property (DataTextField) and Value property (DataValueField) of the checkbox. Text displays can be formatted differently from their default displays by supplying a DataTextFormatString for the CheckBoxList to include additional text or formatting tags.
The GridView is initially populated with records having "Database" as their BookType value. At the same time, the CheckBoxList's OnDataBound event handler calls subprogram Preselect_Checkbox to check the first checkbox in the list to correspond with this set of displayed records. This same technique is used for the similar RadioButtonList application.
After checkbox selections are made, the Get_Book_Types subprogram is called by the button click. First, a check is made to determine if any checkboxes have been selected by iterating the list and testing each item's Selected property.
Sub Get_Book_Type (Src As Object, Args As EventArgs) '-- Determine if any boxes are checked Dim FoundChecked = False Dim Item As ListItem For Each Item In BookList.Items If Item.Selected Then FoundChecked = True Exit For End If Next ... End Sub
If any one checkbox is selected, then a FoundCheck flag is set to indicate this fact. At the completion of the loop, either the flag has been set to "True" (at least one checkbox is selected) or it remains "False" (no checkboxes are selected).
If one or more checkboxes are checked, then an appropriate SQL statement is created to extract selected book types from the database. An initial, partial SELECT string is defined to which is appended one or more WHERE clauses depending on which checkboxes are checked.
Sub Get_Book_Type (Src As Object, Args As EventArgs) ... '-- If boxes are checked, build an SQL statement If FoundChecked = True Then Dim SQLString As String SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty " & _ "FROM Books WHERE " For Each Item in BookList.Items If Item.Selected Then SQLString &= " BookType = '" & Item.Value & "' OR " End If Next ... End If End Sub
Assume, for instance, that the "Database" and "Graphics" checkboxes are checked. After iterating all checkboxes and inserting Item.Value properties (BookTypes) for these checked boxes into the SQL string, the following SELECT statement is produced.
SELECT BookID, BookTitle, BookPrice, BookQty FROM Products WHERE BookType = 'Database' OR BookType = 'Graphics' OR
Additional BookType selections are added to the end of the string if additional checkboxes are checked. At completion of the loop, the composed SELECT statement includes extra " OR " characters on the end of the string which need to be removed. So, the Visual Basic Left() function is used to reassign to variable SQLString all but these last four characters. Finally, an "ORDER BY BookID" clause is added to the end of the statement.
Sub Get_Book_Type (Src As Object, Args As EventArgs) ... '-- If boxes are checked, build an SQL statement If FoundChecked = True Then Dim SQLString As String SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty " & _ "FROM Books WHERE " For Each Item in BookList.Items If Item.Selected Then SQLString &= " BookType = '" & Item.Value & "' OR " End If Next SQLString = Left(SQLString, Len(SQLString) - 4) SQLString &= " ORDER BY BookID" BookSource2.SelectCommand = SQLString ... End If End Sub
A final SQL statement is produced in the format,
SELECT BookID, BookTitle, BookPrice, BookQty FROM Products WHERE BookType = 'Database' OR BookType = 'Graphics' ORDER BY BookID
and is assigned as the SelectCommand property of the AccessDataSource that populates the GridView, producing a list of those product types.
If no checkboxes are checked, then the GridView produces its original display of "Database" records as given by the AccessDataSource that populates the GridView when the page opens. If no checkboxes are checked, then, all that is required is to programmatically check the checkbox for this book type.
Sub Get_Book_Type (Src As Object, Args As EventArgs) ... '-- If boxes are checked, build an SQL statement If FoundChecked = True Then Dim SQLString As String SQLString = "SELECT BookID, BookTitle, BookPrice, BookQty " & _ "FROM Books WHERE " For Each Item in BookList.Items If Item.Selected Then SQLString &= " BookType = '" & Item.Value & "' OR " End If Next SQLString = Left(SQLString, Len(SQLString) - 4) SQLString &= " ORDER BY BookID" BookSource2.SelectCommand = SQLString '-- Otherwise, check the first checkbox Else BookList.Items(0).Selected = True End If End Sub