Set checked items in checkedlistbox from list or dataset
Asked Answered
D

3

6

I have a CheckedListBox and I would like to check all the items that are in another List. This code does not work since the CheckedItems property is read-only and the types do not match, but it gives the best idea of what I want to do.

    checkedListBox1.DataSource = DataSetSelectAll().Tables[0];
    checkedListBox1.ValueMember = "id_table";
    checkedListBox1.DisplayMember = "name";

    List<tableClass> list = MyCheckedList();
    checkedListBox1.CheckedItems = list;

I know this is wrong but do not know how to explain it better.

Dudeen answered 3/11, 2012 at 1:25 Comment(1)
You will have to iterate through list and then set the listbox items to checked.Clove
S
17

Its not possible to set(check) many items at a time like this, checkedListBox1.CheckedItems = list;

better you can use for loop like:

List<tableClass> list = MyCheckedList();
for (int count = 0; count < checkedListBox1.Items.Count; count++)
{
  if (list.Contains(checkedListBox1.Items[count].ToString()))
  {
    checkedListBox1.SetItemChecked(count, true);
  }
}
Standardize answered 3/11, 2012 at 7:1 Comment(1)
better use SetItemCheckState(), to be sure that items also get unchecked when needed.Corene
C
1

I'm not sure why, but I SetItemChecked(index, tf) wasn't giving me what I wanted. This is how I solved it - explicitly setting the CheckedState.

for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
    if (boolList[i])
    {
        myCheckedListBox.SetItemCheckState(i, CheckState.Checked);
    } else
    {
        myCheckedListBox.SetItemCheckState(i, CheckState.Unchecked);
    }
}
Chemush answered 26/2, 2020 at 18:28 Comment(1)
This answer worked for me. It can be simplified by exchanging the while if/else by: DI_Listbox.SetItemCheckState(i, DI[i]?CheckState.Checked: CheckState.Unchecked);Corene
C
0

andy's answer is right but I have an easier solution. My solution works in windows application.

DataTable dt = MyCheckedList();
foreach (DataRow dr in dt.Rows)
{
      for (int i = 0; i < checkedListBox1.Items.Count; i++)
       {
          if (dr["valueMember"].ToString() == ((DataRowView)checkedListBox1.Items[i])[0].ToString())
            {
                checkedListBox1.SetItemChecked(i, true);
            }
       }
}

Note: dt must fill with a dataTable which has all checkedList Values.

Courtroom answered 15/1, 2018 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.