Windows Forms CheckedListBox Control in C# and Vb.Net

← PrevNext →

The Windows Forms “CheckedListBox” control is used to display data in a list format which allows users to check or uncheck the items in the listbox. By default, it shows a small square box before each item in the list, which is unchecked until the user, decides to check it or in other words select it.

checkedlistbox in windows forms

Data or items can be filled in the CheckedListBox manually either during designing the form or dynamically at run time. Data can also be populated by connecting the control with a database object and extract data from it.

Syntax

CheckedListBox.Items.Add()

CheckedListBox.Items.Add("Computer Architecture")
CheckedListBox.Items.Add("Popular Science")

Here in this article I'll show you how to populate data (dynamically) into a CheckedListBox and also find out which items in the list is checked. Obviously, this will help users to choose particular item from list and later use the item from various purposes.

How this works?

On the windows form, add a CheckedListBox and a Button control. The Click event of the button will iterate through the listbox and show the checked items only. Items in the CheckedListBox will be populated during the loading of the form and data will be extracted from an SQL server database table called dbo.books.

Also Read: Bind and Show a ComboBox in a DataGridView Cell

Code Behind (C#)
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CheckListBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SqlDataAdapter SqlAdapter = null;
        DataSet ds = new DataSet();

        private void Form1_Load(object sender, EventArgs e)
        {
            Populate_DataSet();
            FillCheckListBox();
        }

        private void Populate_DataSet()
        {
            string s_ConnString = "Data Source=DNA_CLASSIFIED;Persist Security Info=False;Initial " +
                "Catalog=BookStore;User Id=sa;Password=123;Connect Timeout=30;";

            using (SqlConnection con = new SqlConnection(s_ConnString))
            {

                string sBooks = "SELECT *FROM dbo.BOOKS";

                SqlAdapter = new System.Data.SqlClient.SqlDataAdapter(sBooks, con);
                SqlAdapter.Fill(ds, "BookName");
            }
        }

        private void FillCheckListBox()
        {
            DataRow row = null;
            int iRowCnt = 0;

            lstBooks.Items.Clear();

            foreach (DataRow row_1 in ds.Tables["BookName"].Rows)
            {
                row = row_1;
                lstBooks.Items.Add(ds.Tables["BookName"].Rows[iRowCnt][1]);
                iRowCnt = iRowCnt + 1;
            }
        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            if (lstBooks.Items.Count > 0)
            {
                for (int i = 0; i <= lstBooks.CheckedItems.Count - 1; i++)
                {
                    string s_Value = lstBooks.CheckedItems[i].ToString();
                    MessageBox.Show(s_Value);
                }
            }
        }

    }
}
Vb.Net
Option Explicit On

Imports System.Data.SqlClient

Public Class Form1

    Dim SqlAdapter As SqlDataAdapter
    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Populate_DataSet()
        FillCheckListBox()
    End Sub

    Private Sub Populate_DataSet()
    
        Dim s_ConnString = "Data Source=DNA_CLASSIFIED;Persist Security Info=False;" & _
            "Initial Catalog=BookStore;User Id=sa;Password=123;Connect Timeout=30;"

        Using con As New SqlConnection(s_ConnString)

            Dim sBooks As String = "SELECT *FROM dbo.BOOKS"

            SqlAdapter = New System.Data.SqlClient.SqlDataAdapter(sBooks, con)
            SqlAdapter.Fill(ds, "Books")
        End Using
        
    End Sub

    Private Sub FillCheckListBox()
    
        Dim row As DataRow
        Dim iRowCnt As Integer = 0

        lstBooks.Items.Clear()

        For Each row In ds.Tables("Books").Rows
            lstBooks.Items.Add(ds.Tables("Books").Rows(iRowCnt).Item(1))
            iRowCnt = iRowCnt + 1
        Next
        
    End Sub

    Private Sub btSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles btSelect.Click
    
        If lstBooks.Items.Count > 0 Then
            For i = 0 To lstBooks.CheckedItems.Count - 1
                MsgBox(lstBooks.CheckedItems(i))
            Next
        End If
        
    End Sub
End Class

After you have designed and run the program, you might have notice that while selecting the checkboxes on the control you have to click the item “twice” to actually select it.

This is the default behavior of this control. The first click sets the focus on the item and second click actually selects or checks the item. This can sometimes be very annoying since it doubles the time taken to select the items of our choice. There is a property which allows the user to check items on a single click.

Property CheckOnClick

This property is set to indicate that when an item on the CheckedListBox is clicked it must be instantly selected. The property accepts a Boolean value, which is true or false.

C#

CheckedListBox.CheckOnClick= true;

Vb.Net

CheckedListBox.CheckOnClick = True

Set the value as true at design time or during the loading of the form. To set the value at design time, select the CheckedListBox in the form design view and right click to open the properties window. Look for CheckOnClick property in the list and choose True from the dropdown list.

So now you know that the default value of this property is False. It has to be explicitly set so that your users do not complaint about this being slow.

Property MultiColumn

The MultiColumn property is another useful property in its disposal. At times the list can be huge and showing the entire list on a single form can be difficult. Though it shows scroll bars both horizonally and vertically, we can display the list of items in multiple columns.

This property like the previous one which we have discussed, accepts Boolean values. As usual the value for this property is set a False by default. So we need to set it True explicitly either during design time or at run time.

C#

CheckedListBox.MultiColumn = true;

Vb.Net

CheckedListBox.MultiColumn = True

checkedlistbox with multicolumn property

Property ColumnWidth

With MultiColumn property set as “True”, we also need to set the width of columns, in order to show the items clearly (without overlaping) incase the string is big. To do this we will add the ColumnWidth property, which accepts interger values. This will either shrink or increase the width of each column.

CheckedListBox.ColumnWidth = 200
Thought You Should

The MultiColumn property will be practically visible only when the height of the CheckedListBox is less or it is not long enough to show the entire list. So to see this property in action, we suggest you reduce the height of the control and increase the width of the control on the form.

Conclusion

The CheckedListBox is an extension of a ListBox control and has very similar properties and functionalities like the ListBox. It displays a huge list of items and also can be checked or unchecked. Though we have discussed few properties, it actually has many other useful properties that are worth exploring. Share with us your thoughts about it and also let us know if you have found anything that is worth discussing here on this website.

← PreviousNext →