以编程方式检查复选框列表中的项目,其中文本等于我想要的
在C#中,我试图检查CheckBoxList中的项目,其中文本等于我的要求。
我会修改代码以检查数据库中存在的项目。
如果你想要一个例子,我需要选择等于abc的checklistbox项
假设CheckedListBox中的项是字符串:
for (int i = 0; i < checkedListBox1.Items.Count; i++) { if ((string)checkedListBox1.Items[i] == value) { checkedListBox1.SetItemChecked(i, true); } }
要么
int index = checkedListBox1.Items.IndexOf(value); if (index >= 0) { checkedListBox1.SetItemChecked(index, true); }
基于ASP.NET CheckBoxList的示例
abc def 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"); }
全部归功于@Jim Scott – 只需添加一下。 (ASP.NET 4.5和C#)
对此进行更多的reflection…如果将CheckBoxList作为对象传递给方法,则可以将其重用于任何CheckBoxList。 您也可以使用文本或值。
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);`
//多项选择:
private void clbsec(CheckedListBox clb, string text) { for (int i = 0; i < clb.Items.Count; i++) { if(text == clb.Items[i].ToString()) { clb.SetItemChecked(i, true); } } }
使用==>
clbsec(checkedListBox1,"michael"); or clbsec(checkedListBox1,textBox1.Text); or clbsec(checkedListBox1,dataGridView1.CurrentCell.Value.toString());