Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 681
Peter Roche Avatar asked Feb 07 '12 23:02

Peter Roche


2 Answers

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);
  }
like image 54
wdavo Avatar answered Sep 29 '22 13:09

wdavo


Example based on ASP.NET CheckBoxList

<asp:CheckBoxList ID="checkBoxList1" runat="server">
    <asp:ListItem>abc</asp:ListItem>
    <asp:ListItem>def</asp:ListItem>
</asp:CheckBoxList>


private void SelectCheckBoxList(string valueToSelect)
{
    ListItem listItem = this.checkBoxList1.Items.FindByText(valueToSelect);

    if(listItem != null) listItem.Selected = true;
}

protected void Page_Load(object sender, EventArgs e)
{
    SelectCheckBoxList("abc");
}
like image 38
Jim Scott Avatar answered Sep 29 '22 13:09

Jim Scott