When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Message Board
Related Web Technologies
User Tips!
Coding Tips

Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
Web Hosts
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
Print this Page!
Published: Wednesday, May 7, 2003

Pre-Selecting Items in a CheckBoxList Control

By John Jakovich


A common task in Web programming is the preselection of checkboxes in Web forms. Checkboxes can be used in any situation in which we allow users to select more than one option in a form. For example, you may have a form in which you ask users to select their interests from a list of options, or perhaps select product categories that they are interested in. If you allow your users to select checkbox options then you should also preselect their options when they return to edit their choices. In classic ASP this was accomplished by writing the HTML checkboxes in code and programmatically determining which checkboxes to add the CHECKED parameter to. Fortunately ASP.Net presents a much more elegant solution to the problem.

- continued -

ASP.NET represents a fundamental shift in the way we should think about Web forms programming. The separation between code and presentation means that we are no longer required to dynamically write HTML (although you still can). Instead we have numerous web form objects at our disposal, each with properties, methods, collections and events that can be manipulated to elicit the desired behavior in our Web forms. This is light years ahead of classic ASP, but it does present a learning curve, especially when trying to determine which properties and methods to use in order to get the behavior we want in our forms. This is true when attempting to preselect items in a databound CheckBoxList Control.

Examining the CheckBoxList Control

ASP.NET presents a new way to create Web forms. Each form element is an object; we are no longer required to explicitly write HTML in our applications. In many cases we can use ASP.NET controls to achieve the functionality that we had to "hand code" in classic ASP. In ASP.NET the CheckBoxList control allows you to create multiselection checkbox groups.

The following markup shows the syntax for a sample CheckBoxList control, one that has six options:

<asp:checkboxlist id="CheckBoxList1" runat="server" RepeatColumns="2">
	<asp:ListItem Value="reading">reading</asp:ListItem>
	<asp:ListItem Value="sports">sports</asp:ListItem>
	<asp:ListItem Value="music">music</asp:ListItem>
	<asp:ListItem Value="travel">travel</asp:ListItem>
	<asp:ListItem Value="art">art</asp:ListItem>
	<asp:ListItem Value="nature">nature</asp:ListItem>

This control will render six checkboxes, one for each ListItem.

Creating DataBound CheckBoxLists

This CheckBoxList will work fine but in the real world your CheckBoxLists will probably be bound to a data source enabling you to create the ListItems dynamically. DataBinding any ASP.NET control is very easy, if you're not familiar with DataBinding here are the basic steps:

  1. Establish a connection to a data source and retrieve the results in a DataSet or DataReader.
  2. Set the DataSource property of your control to the DataSet or DataReader created in step 1.
  3. Call the DataBind() method of the control you are binding.

Lets take a look at a DataBound CheckBoxListControl. We'll create a table called interest that contains the options our members can select from. The data/schema for this table can be seen in the diagram to the right. (Note that the interest table has a single column called interest.)

Recall that the first step in the databinding process is to load the database data into a DataSet or DataReader. Let's examine how to load the contents of the interest table into a DataReader. First we set up the ADO.NET SqlConnection and SqlCommand objects. (If you are using a database other than Microsoft SQL Server you would want to use the classes OleDbConnection and OleDbCommand instead.)

SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand objCmd = new SqlCommand("select interest from interest",objConn); objConn.Open();

Next we set the DataSource property of the CheckBoxList control to a SqlDataReader object derived from our SqlCommand object. Then we call the DataBind() method.

CheckBoxList1.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection);

After our CheckBoxList control has been bound it can be referenced in code by its ID property, in this case the ID is CheckBoxList1.

When binding database data to a CheckBoxList, you do not need to explicitly specify the CheckBoxList's ListItems. However, you should specify two CheckBoxList properties: DataTextField and DataValueField. The DataTextField determines what field from the database data being bound to the CheckBoxList will be displayed as the text for each checkbox. The DataValueField property determines what field from the database data being bound to the CheckBoxList will be assigned to the checkbox's Value property. (We'll discuss the Text and Value properties of the CheckBoxList's items in more detail shortly.)

For this example, we want the text and value of each created checkbox to have the value from the interest field. Therefore, we'd set the DataTextField and DataValueField properties to interest. All of this can be done in the HTML portion, meaning our CheckBoxList's declaration would look like:

<asp:checkboxlist id="CheckBoxList1" runat="server" RepeatColumns="2"
      DataTextField="interest" DataValueField="Interest" />

Compare this declaration to the first example we saw. Note that the one above does not explicitly indicate its various ListItems, because these values are obtained automatically in the databinding process.

Examining the CheckBoxList's ListItems

When using a CheckBoxList without databinding, each ListItem explicitly specified in the CheckBoxList control will render a single checkbox. Glancing back at the first example we saw in this article, there were six checkboxes (reading, sports, music, travel, art, nature). When the CheckBoxList is populated via databinding, there will be a checkbox for each row in the data bound to the CheckBoxList.

Whether the CheckBoxList is populated manually or via databinding, each ListItem can be referenced programmatically via the CheckBoxList's Items property. Specifically, each ListItem is represented by a ListItem object in the Items collection. The ListItem object contains methods and properties that can be used to preselect the checkboxes when the CheckBoxList control is rendered by ASP.NET. The three germane properties of the ListItem object are Text and Value, two string properties, and Selected, a Boolean property determining if the particular CheckBoxList checkbox is checked or not.

Selecting a CheckBoxList CheckBox

Recall that the motivation for this article is to examine how to pre-select checkboxes in a CheckBoxList. In order to accomplish this, we must be able to programmatically check a particular checkbox. The first step to preselecting a checkbox is to reference the ListItem object that corresponds to the checkbox that we want to check. The simplest way to accomplish this is to use the FindByValue() method of the CheckBoxList's Items collection. The FindByValue method allows us to search the Items collection for a ListItem by its Value property (there is also a FindByText() method).

The following creates a ListItem object named myListItem, which references the "sports" checkbox:

ListItem myListItem = CheckBoxList1.Items.FindByValue("sports");

Once we have a ListItem object for a checkbox, we can set the Selected property to True like so:

myListItem.Selected = true;

This will cause the "sports" checkbox to be selected (checked) when the CheckBoxList control is rendered.

Preselecting Checkbox Items Using Values from a Database

In this example we will ask our users to select their interests from a list of checkbox items. Once the user selects their interests and submits the form, we'll store the options in a table called member_interest. Some sample data for this database table is shown to the right.

In order to preselect the checkboxes that correspond to John's interests we will iterate through his interests using a SqlDataReader. For each of John's interests we'll find the corresponding ListItem in the CheckBoxList and set its Selected property to True. To summarize, our basic steps will be:

  1. Iterate through John's interests (sports, travel, music) using a SqlDataReader.
  2. For each of John's interests, use the FindByValue() method of the CheckBoxList Items collection to create a ListItem object for the checkbox we want to select.
  3. Set the Selected property of the ListItems object to True, thereby preselecting the checkboxes that correspond to John's interests.

The first thing we need to do is create a SqlDataReader object that contains John's interests. This can be accomplished with the following code:

objCmd = new SqlCommand("select * from member_interest where name= 'John'",objConn);
SqlDataReader objReader = objCmd.ExecuteReader();

Now that we have a SqlDataReader containing the values for the checkboxes we want to preselect, the next step is to iterate through the SqlDataReader, reference the appropriate ListItem object corresponding to each of John's interests, and set its Selected property to True. This can be accomplished using the following:

while (objReader.Read())
   // create a ListItem object corresponding to the current interest, then set the selected
   // property to true
   ListItem currentCheckBox = cblInterest.Items.FindByValue(objReader["interest"].ToString());
   if (currentCheckBox != null)
      currentCheckBox.Selected = true;

That's all there is to it! The screenshot to the right shows what John will see when he visits the page to edit his choices after he has already indicated his interests.

Putting It All Together

Put the code we've examined throughout this article in the Page_Load event handler, so that it is run when the page is loaded. Since we only want the CheckBoxList control to be data bound on the page's first load (and not on subsequent postbacks), we place this logic in an if statement, running the code only if the Page.IsPostBack property is False. The complete ASP.NET Web page code and HTML markup can be seen below:

private void Page_Load(object sender, System.EventArgs e)
   if (!IsPostBack)
      SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
      SqlCommand objCmd = new SqlCommand("select interest from interest order by interest",objConn);
      cblInterest.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection);

      objCmd = new SqlCommand("select * from member_interest where name= 'John'",objConn);
      SqlDataReader objReader = objCmd.ExecuteReader();

      while (objReader.Read())
         ListItem currentCheckBox = cblInterest.Items.FindByValue(objReader["interest"].ToString());
         if (currentCheckBox != null)
            currentCheckBox .Selected = true;

<asp:checkboxlist id="CheckBoxList1" runat="server" RepeatColumns="2"
      DataTextField="interest" DataValueField="Interest" />


Preselecting items in a CheckBoxList control can be accomplished by setting the Selected property for each ListItem object in the CheckBoxList Items collection. This differs from classic ASP because we are no longer required to dynamically write HTML in code. Instead we can take advantage of the object-oriented nature of ASP.NET, making our Web form programming much cleaner and more versatile.

Although there will be a learning curve associated with the new web forms programming techniques, there are numerous advantages to the new ASP.NET object oriented architecture. Don't be afraid to explore and investigate the new objects, methods, properties and collections available in ASP.NET.

Happy Programming!

  • By John Jakovich

  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article