CheckedListBox – 按文本搜索项目
我有一个绑定到DataTable
的CheckedListBox
。 现在我需要以编程方式检查一些项目,但我发现SetItemChecked(...)
方法只接受项目索引。
是否有一种实用的方法来获取文本/标签的项目,而不知道项目索引?
(注意:我对WinForms的经验有限……)
您可以实现自己的SetItemChecked(string item);
private void SetItemChecked(string item) { int index = GetItemIndex(item); if (index < 0) return; myCheckedListBox.SetItemChecked(index, true); } private int GetItemIndex(string item) { int index = 0; foreach (object o in myCheckedListBox.Items) { if (item == o.ToString()) { return index; } index++; } return -1; }
checkListBox使用object.ToString()
来显示列表中的项目。 您可以实现一个搜索所有对象的方法.ToString()来获取项索引。 获得项索引后,可以调用SetItemChecked(int, bool);
希望能帮助到你。
您可以尝试浏览您的数据表。 您可以在DataTabke.Rows属性上执行foreach或使用SQL语法,如下所示:
DataTable dtTable = ... DataRow[] drMatchingItems = dtTable.Select("label = 'plop' OR label like '%ploup%'"); // I assumed there is a "label" column in your table int itemPos = drMatchingItems[0][id]; // take first item, TODO: do some checking of the length/matching rows
干杯,