CheckedListBox - 按文本搜索项目

dav*_*ooh 9 .net c# checkedlistbox winforms

我有一个CheckedListBox必然的DataTable.现在我需要以编程方式检查一些项目,但我发现该SetItemChecked(...)方法只接受项目索引.

有没有一种实用的方法来通过文本/标签获取项目,而不知道项目索引?

(注意:我对WinForms的经验有限......)

Dan*_*lba 11

你可以实现自己的 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;
    }
Run Code Online (Sandbox Code Playgroud)

checkListBox用于object.ToString()显示列表中的项目.您可以实现一个搜索所有对象的方法.ToString()以获取项索引.获得项目索引后,即可致电SetItemChecked(int, bool);

希望能帮助到你.