CheckedListBox - Search for an item by text
Asked Answered
C

3

10

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

Cariole answered 2/2, 2012 at 9:12 Comment(0)
M
11

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.

Mccullum answered 2/2, 2012 at 9:25 Comment(3)
Maybe it depends on the binding with a DataTable, but o.ToString() in my case returns "System.Data.DataRowView", so I think I have to use myCheckedListBox.GetItemText(o)...Cariole
When I saw "practical way" I mean an existing method to do it... But it seems that anything like that is provided by the framework, so I'll implement my own method, as you suggest. Thank you very much.Cariole
Thanks a lot for this method - most things I've seen are fairly dirty or too trivial. For my purpose I was loading XML and populating checked items based on settings using custom objects.Grew
M
0

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,

Marrilee answered 2/2, 2012 at 9:25 Comment(0)
D
0

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];
Deflocculate answered 22/12, 2022 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.