Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckedListBox - Search for an item by text

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

like image 502
davioooh Avatar asked Feb 02 '12 09:02

davioooh


1 Answers

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.

like image 132
Daniel Peñalba Avatar answered Oct 14 '22 10:10

Daniel Peñalba