我有一个 CheckedListBox,我想自动选中其中的一个项目。
CheckedItems
集合不允许你向其中添加内容。
有什么建议?
我有一个 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中的所有项目,并检查(或取消选中)具有指定索引的项目。
例如,我的代码片段循环遍历指定的程序名称,如果该程序包含在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));
}
}
list.SetItemChecked(i, !list.GetItemChecked(i));
来反转选择。 - ccalboniSetItemChecked(0, true)
时,GetItemChecked(0)
仍然返回false
! - Matt ArnoldSetItemChecked
不起作用,但我发现CheckedListBox.Items.Add("Some Item", true)
不起作用,而CheckedListBox.AddItem("Some Item", true)
是可以的! - Matt Arnold