19

在 C# 中,我试图检查 CheckBoxList 中文本等于我需要的项目。

我会修改代码以检查数据库中存在的项目。

如果您想要一个示例,我需要选择等于 abc 的复选框项目

4

5 回答 5

45

假设 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);
  }
于 2012-02-07T23:52:23.233 回答
10

基于 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");
}
于 2012-02-08T00:00:28.177 回答
4

全部归功于@Jim Scott - 只是增加了一点。(ASP.NET 4.5 和 C#)

再重构一下……如果将 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);`
于 2014-05-06T19:10:17.890 回答
0

我尝试添加动态创建的 ListItem 并分配选定的值。

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

避免使用绑定数据源,因为它不会绑定数据库中的选中/未选中。

于 2019-08-02T18:31:15.320 回答
0

//多选:

          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());
于 2017-01-07T19:18:37.453 回答