54

我有一个 CheckedListBox,我想自动勾选其中的一项。

CheckedItems集合不允许您向其中添加内容。

有什么建议么?

4

6 回答 6

78

您需要SetItemChecked使用相关物品致电。

文档CheckedListBox.ObjectCollection有一个示例,该示例检查集合中的所有其他项目。

于 2008-12-16T09:48:31.513 回答
23

这是您可以一次选择/勾选或取消选择/取消勾选所有项目的方式:

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);
        }
    }  
}
于 2012-07-19T18:27:39.820 回答
8

在我的程序中,我使用了以下技巧:

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);
}
于 2015-11-24T20:30:11.430 回答
5

假设您想在单击按钮时检查项目。

private void button1_Click(object sender, EventArgs e)
{
    checkedListBox1.SetItemChecked(itemIndex, true);
}

其中 itemIndex 是要检查的项目的索引,它从 0 开始。

于 2015-01-25T01:30:49.463 回答
3

采用:

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);
}
于 2015-02-13T03:50:30.173 回答
2

我使用扩展名:

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));
    }
}
于 2017-08-17T06:22:17.320 回答