Reputation: 1764
I am working on a Windows form Application.
I want to check/uncheck
all checkboxes in checkedlistbox.
I am using following code to generate checkboxes dynamically.
var CheckCollection = new List<CheckedBoxFiller>();
foreach (DataRow dr in dt.Rows)
CheckCollection.Add(new CheckedBoxFiller {
Text = dr["ImageName"].ToString(),
Value = dr["ImageId"].ToString()
});
chklbEvidenceTags.DataSource = CheckCollection;
chklbEvidenceTags.DisplayMember = "Text";
chklbEvidenceTags.ValueMember = "Value";
And this is the CheckboxFiller class
private class CheckedBoxFiller {
public string Text { get; set; }
public string Value { get; set; }
}
Now I want to check/Uncheck
all checkboxes
. How can I achieve this?
Any help would be useful.
Upvotes: 13
Views: 43631
Reputation: 4316
Check/Uncheck all list items written below code:
if (checkBox1.Checked)
{
for (int i = 0; i < chkboxlst.Items.Count; i++)
{
chkboxlst.SetItemChecked(i, true);
}
}
else
{
for (int i = 0; i < chkboxlst.Items.Count; i++)
{
chkboxlst.SetItemChecked(i, false);
}
}
Upvotes: 6
Reputation: 1
To Uncheck/Check all listItems Do the below Code:
boolean state =false;//False->Uncheck,true->Check
for (int i = 0; i < chklistbox.Items.Count; i++)
chklistbox.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
Upvotes: -3
Reputation: 492
If you have a large Items list, this approach may be a little more efficient for unchecking items. It requires you only cycle through the items that are actually checked:
private void UncheckAllItems()
{
while (chklistbox.CheckedIndices.Count > 0)
chklistbox.SetItemChecked(chklistbox.CheckedIndices[0], false);
}
And if you use multiple CheckedListBox controls throughout your project and wanted to take it a step further, it could be added as an extension method:
public static class AppExtensions
{
public static void UncheckAllItems(this System.Windows.Forms.CheckedListBox clb)
{
while (clb.CheckedIndices.Count > 0)
clb.SetItemChecked(clb.CheckedIndices[0], false);
}
}
Extension method call:
chklistbox.UncheckAllItems();
Upvotes: 16
Reputation: 1764
I found solution.
for (int i = 0; i < chklistbox.Items.Count; i++)
chklistbox.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
state
is boolen
value.
Upvotes: 26