<asp:CheckBoxField> Control

The <asp:CheckBoxField> is a GridView control used to display the value of a Boolean data field as a checkbox. In a Microsoft Access database this field is defined as a "Yes/No" field type displaying a checkbox. A checked box is evaluated as True and an unchecked box as False. These checks are duplicated in the CheckBoxField control.

A CheckBoxField is added as a GridView column by coding it inside the <Columns> section along with BoundField, ImageField, and other field control types. Properties associated with this control are shown in Figure 7-8.

<asp:GridView id="id" Runat="Server"
  AutoGenerateColumns="False"
  ... >
	
  <Columns>
	
    <asp:CheckBoxField
      DataField="field"
      FooterText="string"
      HeaderText="string"
      SortExpression="field"
      Text="string"
			
      HeaderStyle-property="value"...
      ItemStyle-property="value"...
      FooterStyle-property="value"...
    />
    ...
	
  </Columns>
	
</asp:GridView>
Figure 7-8. General format for <asp:CheckBoxField> control of <asp:GridView> control.

To specify the database field to display in a CheckBoxField set the DataField property to the field's name. You can display a caption to the right of each checkbox by setting its Text property. A SortExpression can be coded for the control. Usually, this setting indicates a different sort field from the CheckBoxField as discussed later. Common style settings can be applied to the field as well as to header and footer rows.

A GridView table that displays the BookSale field from the BooksDB.mdb database is shown below. This column indicates whether the product is offered at a special sale price. Notice that the checkboxes are dimmed, indicating that they are disabled to prevent changing the checkmarks.

IDTitleOn Sale
SW111Java How to Program
SW222C Programming Language
SW333Programming C#
SW444Programming PHP
SW555Visual Basic.NET Programming

Figure 7-9. Using a CheckBoxField column in a GridView.
<asp:AccessDataSource id="BookSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT BookID, BookTitle, BookSale FROM Books 
                 WHERE BookType='Software' ORDER BY BookID"/>
	
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AutoGenerateColumns="False"
  CellPadding="3"
    HeaderStyle-BackColor="#707070"
    HeaderStyle-ForeColor="#FFFFFF">

  <Columns>
	
  <asp:BoundField
    DataField="BookID"
    HeaderText="ID"/>
	
  <asp:BoundField
    DataField="BookTitle"
    HeaderText="Title"/>

  <asp:CheckBoxField
    HeaderText="On Sale"
    DataField="BookSale"
    ItemStyle-HorizontalAlign="Center"/>
	
  </Columns>

</asp:GridView>
Listing 7-6. Code for GridView with CheckBoxField column.

It is important to remember that the DataField must be of a True or False data type. In the case of an Access database, the field type is "Yes/No," although its value is interpreted as True or False.