简体   繁体   English

CheckedListBox - 按文本搜索项目

[英]CheckedListBox - Search for an item by text

I have a CheckedListBox bound to a DataTable .我有一个绑定到DataTableCheckedListBox Now I need to check some items programmatically, but I find that the SetItemChecked(...) method only accepts the item index.现在我需要以编程方式检查一些项目,但我发现SetItemChecked(...)方法只接受项目索引。

Is there a practical way to get an item by text/label, without knowing the item index?有没有一种实用的方法可以在不知道项目索引的情况下通过文本/标签获取项目?

(NOTE: I've got limited experience with WinForms...) (注意:我对 WinForms 的经验有限......)

You can implement your own SetItemChecked(string item); 您可以实现自己的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;
    }

The checkListBox uses object.ToString() to show items in the list. checkListBox使用object.ToString()来显示列表中的项目。 You you can implement a method that search across all objects.ToString() to get an item index. 您可以实现一个搜索所有对象的方法.ToString()来获取项索引。 Once you have the item index, you can call SetItemChecked(int, bool); 获得项目索引后,可以调用SetItemChecked(int, bool);

Hope it helps. 希望能帮助到你。

I am answering it very late, I hope it will help someone.我很晚才回答,我希望它能帮助别人。 If you want to find any item by name we can do it in two steps.如果您想按名称查找任何项目,我们可以分两步完成。 First get index of item by text and then we can get actual item with the help of index.首先通过文本获取项目的索引,然后我们可以借助索引获取实际项目。

var selectedItemIndex = cbxList.Items.IndexOf("sometext");
var selectedItem = cbxList.Items[selectedItemIndex];

You may try to browse your Datatable. 您可以尝试浏览数据表。 YOu can do a foreach on the DataTabke.Rows property or use SQL syntax as below: 您可以在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

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM