CheckedListBox - Search for an item by text

蹲街弑〆低调 提交于 2019-12-09 16:17:54

问题


I have a CheckedListBox bound to a DataTable. Now I need to check some items programmatically, but I find that the SetItemChecked(...) method only accepts the item index.

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...)


回答1:


You can implement your own 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. You you can implement a method that search across all objects.ToString() to get an item index. Once you have the item index, you can call SetItemChecked(int, bool);

Hope it helps.




回答2:


You may try to browse your Datatable. YOu can do a foreach on the DataTabke.Rows property or use SQL syntax as below:

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,



来源:https://stackoverflow.com/questions/9109675/checkedlistbox-search-for-an-item-by-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!