CheckedListBox - element search by text

I have a CheckedListBox related to a DataTable . Now I need to check some elements programmatically, but I found that the SetItemChecked(...) method accepts only the index of the element.

Is there a practical way to get an element by text / label without knowing the index of the element?

(NOTE: I have limited experience with WinForms ...)

+7
source share
2 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; } 

CheckListBox uses object.ToString() to display items in a list. You can implement a search method on all objects. ToString () to get the index of the item. When you have an item index, you can call SetItemChecked(int, bool);

Hope this helps.

+7
source

You can try to view your datatable. You can do foreach in the DataTabke.Rows property or use the SQL syntax as shown 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 

Greetings

0
source

All Articles