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 developrs 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