Programmatically Check an Item in Checkboxlist where text is equal to what I want
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);
}
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");
}
All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)
Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.
private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
ListItem listItem = lst.Items.FindByValue(valueToSelect);
//ListItem listItem = lst.Items.FindByText(valueToSelect);
if (listItem != null) listItem.Selected = true;
}
//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`
SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`