Programmatically Check an Item in Checkboxlist where text is equal to what I want

Peter Roche picture Peter Roche · Feb 8, 2012 · Viewed 101.3k times · Source

In C#, I am trying to Check an item in a CheckBoxList where the text equals what I require.

I would modify the code to check items that exist in the database.

If you would like an example, I need to select the checklistbox item that equals to abc.

Answer

wdavo picture wdavo · Feb 8, 2012

Assuming that the items in your CheckedListBox are strings:

  for (int i = 0; i < checkedListBox1.Items.Count; i++)
  {
    if ((string)checkedListBox1.Items[i] == value)
    {
      checkedListBox1.SetItemChecked(i, true);
    }
  }

Or

  int index = checkedListBox1.Items.IndexOf(value);

  if (index >= 0)
  {
    checkedListBox1.SetItemChecked(index, true);
  }