【问题标题】:How to set Item checked in a checkedlistbox based on Key value?如何根据键值设置选中列表框中的项目?
【发布时间】:2019-07-10 06:58:59
【问题描述】:

我已经为它绑定了 Id 和值的值的 checkListbox,当检查项目时,我将 Id 保存在数据库中,当加载表单时,我希望根据 Id 检查checkedListbox 项目

我只能根据下面的索引绑定checkedlistbox,我看到的另一种选择是获取值的索引并检查它,但这在我的情况下不起作用,因为我只有checkedlistbox的ID需要检查的项目。

int index = checkedListBox1.Items.IndexOf("42");
checkedListBox1.SetItemChecked(index , true);

这就是我绑定值的方式

ccBoxitem item = new ccBoxitem(a.name, a.id);
checkedListBox1.items.add(item);
public ccBoxitem (string name, int val)
{
    this.name = name;
    this.val = val;
}

如何根据 id 检查checkedlistbox

【问题讨论】:

  • 什么是Id of checkedlistbox item
  • 更新了我的帖子
  • 所以valid
  • 是的 val 是一个 Id

标签: c# winforms checkedlistbox


【解决方案1】:

例如,您可以遍历您的项目,然后检查您想要的:

 private void CheckItem(int id)
 {
     for (int i = 0; i < checkedListBox1.Items.Count; i++)
     {
         if ((checkedListBox1.Items[i] as ccBoxitem)?.val == id)
         {
             checkedListBox1.SetItemChecked(i, true);
         }
     }
 }

用法:

var id = GetId();
CheckItem(id);

【讨论】:

    【解决方案2】:

    您可以使用下面的方法,它会先根据其值选择需要的项目,然后检查所选项目

    void CheckItem(CheckedListBox checkedListBox, int id)
    {
        checkedListBox.SelectedItem = checkedListBox.Items.OfType<ccBoxitem>().ToList().FirstOrDefault(i => i.val == id);
        checkedListBox.SetItemChecked(checkedListBox.SelectedIndex, true);
        checkedListBox.SelectedItem = null; // To clear selection if needed
    }
    

    你可以这样称呼它

    CheckItem(checkedListBox1, 3);
    
    CheckItem(checkedListBox1, 6);
    

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多