How to: Respond to Checking Items in CheckedListBoxControl

  • 2 minutes to read

The code below shows a message when a list box item's check state changes and prevents the first item from being checked.

using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

for (int i = 0; i < 10; i++)
    checkedListBoxControl1.Items.Add(new CheckedListBoxItem(i, "Item " + i.ToString()));
checkedListBoxControl1.ItemChecking += CheckedListBoxControl1_ItemChecking;
checkedListBoxControl1.ItemCheck += checkedListBoxControl1_ItemCheck;

private void CheckedListBoxControl1_ItemChecking(object sender, ItemCheckingEventArgs e) {
    CheckedListBoxControl checkedListBox = (CheckedListBoxControl)sender;
    CheckedListBoxItem item = (CheckedListBoxItem)checkedListBox.GetItem(e.Index);
    if (item.Description == "Item 0") {
        MessageBox.Show($"You cannot change the {item.Description} item check state.");
        e.Cancel = true;
    }
}

private void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e) {
    CheckedListBoxControl checkedListBox = (CheckedListBoxControl)sender;
    CheckedListBoxItem item = (CheckedListBoxItem)checkedListBox.GetItem(e.Index);
    MessageBox.Show($"The {item.Description} item with the {item.Value} value is {item.CheckState}.");
}