我有一个 CheckedListBox,我想自动勾选其中的一项。
该CheckedItems
集合不允许您向其中添加内容。
有什么建议么?
您需要SetItemChecked
使用相关物品致电。
的文档CheckedListBox.ObjectCollection
有一个示例,该示例检查集合中的所有其他项目。
这是您可以一次选择/勾选或取消选择/取消勾选所有项目的方式:
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);
}
}
}
在我的程序中,我使用了以下技巧:
CheckedListBox.SetItemChecked(CheckedListBox.Items.IndexOf(Item),true);
事情是如何工作的:
SetItemChecked(int index, bool value) 是设置特定项目的确切检查状态的方法。您必须指定要检查的项目索引(使用 IndexOf 方法,作为参数指定项目的文本)和检查状态(true 表示项目已检查,false 未检查)。
此方法遍历 CheckedListBox 中的所有项目并检查(或取消选中)具有指定索引的项目。
例如,我的一小段代码 - FOREACH 循环通过指定的程序名称运行,如果该程序包含在 CheckedLitBox ( CLB... ) 中,请检查它:
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);
}
假设您想在单击按钮时检查项目。
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.SetItemChecked(itemIndex, true);
}
其中 itemIndex 是要检查的项目的索引,它从 0 开始。
采用:
string[] aa = new string[] {"adiii", "yaseen", "salman"};
foreach (string a in aa)
{
checkedListBox1.Items.Add(a);
}
现在在您要检查所有内容的地方编写代码:
private void button5_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, true);
}
取消选中所有:
private void button_Click(object sender, EventArgs e)
{
for(int a=0; a<checkedListBox1.Items.Count; a++)
checkedListBox1.SetItemChecked(a, false);
}
我使用扩展名:
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));
}
}