Reputation: 5490
I have a CheckedListBox, and I want to automatically tick one of the items in it.
The CheckedItems
collection doesn't allow you to add things to it.
Any suggestions?
Upvotes: 57
Views: 110917
Reputation: 59956
Use:
string[] aa = new string[] {"adiii", "yaseen", "salman"};
foreach (string a in aa)
{
checkedListBox1.Items.Add(a);
}
Now code where you want to check all:
private void button5_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, true);
}
To uncheck all:
private void button_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, false);
}
Upvotes: 4
Reputation: 1500665
You need to call SetItemChecked
with the relevant item.
The documentation for CheckedListBox.ObjectCollection
has an example which checks every other item in a collection.
Upvotes: 83
Reputation: 91
I use an extension:
public static class CheckedListBoxExtension
{
public static void CheckAll(this CheckedListBox listbox)
{
Check(listbox, true);
}
public static void UncheckAll(this CheckedListBox listbox)
{
Check(listbox, false);
}
private static void Check(this CheckedListBox listbox, bool check)
{
Enumerable.Range(0, listbox.Items.Count).ToList().ForEach(x => listbox.SetItemChecked(x, check));
}
}
Upvotes: 2
Reputation: 161
In my program I've used the following trick:
CheckedListBox.SetItemChecked(CheckedListBox.Items.IndexOf(Item),true);
How does things works:
SetItemChecked(int index, bool value) is method which sets the exact checked state at the specific item. You have to specify index of item You want to check (use IndexOf method, as an argument specify text of item) and checked state (true means item is checked, false unchecked).
This method runs through all items in CheckedListBox and checks (or unchecks) the one with specified index.
For example, a short piece of my code - FOREACH cycle runs through specified program names, and if the program is contained in CheckedLitBox (CLB...), checks it:
string[] ProgramNames = sel_item.SubItems[2].Text.Split(';');
foreach (string Program in ProgramNames)
{
if (edit_mux.CLB_ContainedPrograms.Items.Contains(Program))
edit_mux.CLB_ContainedPrograms.SetItemChecked(edit_mux.CLB_ContainedPrograms.Items.IndexOf(Program), true);
}
Upvotes: 11
Reputation: 3243
Suppose you want to check the item on clicking a button.
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.SetItemChecked(itemIndex, true);
}
Where itemIndex is the index of the item to be checked, it starts from 0.
Upvotes: 6
Reputation: 10247
This is how you can select/tick or deselect/untick all of the items at once:
private void SelectAllCheckBoxes(bool CheckThem) {
for (int i = 0; i <= (checkedListBox1.Items.Count - 1); i++) {
if (CheckThem)
{
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
else
{
checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
}
}
}
Upvotes: 26