How to populate a CheckBoxList from SqlDataSource in c#

Populate a CheckBoxList from SqlDataSource
CheckBoxList is an web server control that provides a multi selection CheckBox group. CheckBoxList control support data binding. so we can populate CheckBoxList with items from a data source control. To bind CheckBoxList control to a data source, first developers need to create a datasource control such as ObjectDataSource, LinqDataSource, SqlDataSource control etc.

DataSource control contains the items to display in the CheckBoxList. After creating DataSource control, developers can call CheckBoxList DataBind method to bind the DataSource to the CheckBoxList control. This method allow developers to programmatically (dynamically) data bind CheckBoxList control at run time.

CheckBoxList control's DataTextFiled and DataValueFiled properties specify which field in the data source to bind to the Text and Value properties of each list item in CheckBoxList control. ChecBoxList ListItem object contains Text and Value properties. Text property text display in the CheckBoxList control and Value property is associated with ListItem object and hidden in the web browser.

We also can use CheckBoxList DataSourceID property to specify DataSource control using declarative syntax. Declarative syntax also support DataTextField and DataValueField properties.

The following c# example code demonstrate us how can we data bind a CheckBoxList with SqlDataSource control to display CheckBoxList items from database data.

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Clicked(object sender,System.EventArgs e) {
        Label1.Text = "You Selected:<br/>";
        foreach (ListItem li in CheckBoxList1.Items){
            if (li.Selected == true){
                Label1.Text += li.Text + "<br/>";

<html xmlns="">
    <head runat="server">
        <title>CheckBoxList example: how to populate CheckBoxList from SqlDataSource in</title>
        <form id="form1" runat="server">
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <hr />
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>" SelectCommand="SELECT [ProductName] FROM [Products]">
                <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="ProductName" RepeatColumns="4" BorderStyle="Solid" BorderColor="Red" BorderWidth="1px">
                <asp:Button ID="Button1" runat="server" Text="Vew Selected Products" OnClick="Button1_Clicked" />
More examples