预定义字符串列表中CheckedListBox中的复选框
本文关键字:复选框 CheckedListBox 预定义 列表 字符串 | 更新日期: 2023-09-27 18:24:03
我有一个checkedListBox(c#),希望在打开窗口时检查其中的一些框。我有一个包含值的List<string>
,如果列表中的值与CheckedListBox中的值相同,我希望它被选中!
我可以让所有的盒子自己检查,但下一部分有问题。如何检查列表框中的值是否等于列表中的任何值?
到目前为止,我拥有的是:
//List of all the strings that I want to check
List<string> categories = new List<string>();
categories.Add("Cat 1");
categories.Add("Cat 2");
categories.Add("Cat 2");
//clBCategory is the CheckedListBox
for (int i = 0; i < clBCategory.Items.Count; i++)
{
clBCategory.SetItemChecked(i, true);
}
CheckedListBox
基本上是object
对象的looly-typed集合。下面的代码很粗糙,但应该足以让你继续:
List<string> categories = new List<sting>();
categories.Add("Cat 1");
categories.Add("Cat 2");
categories.Add("Cat 3");
for (int i = 0; i < clBCategory.Items.Count; i++)
{
if (categories.Contains(clBCategory.Items[i].ToString()))
clBCategory.SetItemChecked(i, true);
}
1)
List<string> categories = new List<sting>();
categories.Add("Cat 1");
categories.Add("Cat 2");
categories.Add("Cat 3");
int index;
//Instead of traversing checkedListBox1 I have traversed List
foreach (string str in list)
{
index = checkedListBox1.Items.IndexOf(str);
if (index < 0) continue;
if (str == checkedListBox1.Items[index].ToString())
{
checkedListBox1.SetItemChecked(index, true);
}
}
我已经测试过了,它运行得非常好:)
2) 此外,我建议您使用类似的集合初始值设定项
list = new List<string>() {"Cat 1","Cat 2","Cat 9"};