Bind CheckedListBox in Windows Form Using C#

This article shows you how to bind a CheckedListbox of a Windows Forms form using C#, where we will use one CheckedListBox control and on a button click the data is bound to the control.

Initial chamber

Step 1

Open Visual Studio 2010, Go to File, then New, Projects and under Visual C# select Windows.

Window form application

You can change the name of the project and can place your project in a different location too. Then press OK.

Step 2

In Solution Explorer you will get your project, add a Service Based Database. This is added by right-clicking, then selecting Add New Item and selecting Service Based Database.

service based database

Database chamber

Step 3

Go to your database (database.mdf) and create a table tbl_Data.  Go to database.mdf, select Table and Add New table. Design your table as in the following:

design table

Show tbl_data:

Table

Design chamber

Step 4

Now open your Form1.cs file, where we will create our design for CheckedListBox Binding.
We will drag CheckedListBox from the toolbox to Form1.cs.

You will see your form as in the following:

Design

Code chamber

Right-click on the blank part of Form1.cs and View Code. Write the following code and then press F5 to run the project.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data.SqlClient;  
  10.   
  11.   
  12. namespace CheckBoxBind  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.              
  20.             
  21.         }  
  22.   
  23.         private void button1_Click(object sender, EventArgs e)  
  24.         {  
  25.   
  26.   
  27.             SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");  
  28.             SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  29.             SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  30.             DataTable dt = new DataTable();  
  31.             sda.Fill(dt);  
  32.   
  33.             for (int i = 0; i < dt.Rows.Count; i++)  
  34.             {  
  35.                 checkedListBox1.Items.Add(dt.Rows[i]["books"].ToString());  
  36.   
  37.             }  
  38.         }     
  39.   
  40.     }  
  41.   
  42.   
  43. }  
Output chamber

Bind CheckBox List

I hope you liked this. Thank you for reading. Have a good day.

Up Next
    Ebook Download
    View all
    Learn
    View all