【问题标题】:Set checkedListBox item checked if valuemember = something如果 valuemember = something,则设置 checkedListBox 项目已选中
【发布时间】:2017-07-03 16:50:29
【问题描述】:

我知道如何将项目设置为选中:

checkedListBox.SetItemChecked(index, true);

但是当我打开带有int[] valueMembers 参数的表单时,我会调用它,所以我想检查每个值成员,它是 = 到这个参数来检查。这是我尝试过的:

    public NovaPoruka(int[] primalacID)
    {
        InitializeComponent();

        foreach(CheckedListBox o in checkedListBox1.Items)
        {
            if(primalacID.Contains(Convert.ToInt32(o.SelectedValue)))
            {
                o.SetItemChecked(o.SelectedIndex, true);
            }
        }
    }

编辑: 我没有看到我在执行此操作之前没有初始化checkedListBox,所以它没有丢弃错误,但现在当我这样做时,我在CheckedListBox o in checkedListBox1.Items 丢弃了我的错误,所以我几乎没有改变,但仍然不知道如何获取 foreach 循环内的当前项目的索引。这是更改的代码:

foreach(Int_String o in checkedListBox1.Items)
{
    if(primalacID.Contains(Convert.ToInt32(o._int)))
    {
            checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
    }
}

当前获取选定索引的方式返回我-1

【问题讨论】:

  • 然后呢?问题是什么?您是否忘记解释为什么此代码不起作用?
  • 它只是没有。它不会检查它并且不会丢弃任何错误
  • 我做了一些修改,所以对你来说可能会更容易
  • 使用普通的 for... 循环,您的索引是 for 迭代中使用的变量
  • 刚刚完成并正在回答。无论如何谢谢:)

标签: c# winforms visual-studio checkedlistbox


【解决方案1】:

我已经做到了。这是最终代码:

for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
    Int_String s = checkedListBox1.Items[i] as Int_String;
    if(primalacID.Contains(s._int))
    {
        checkedListBox1.SetItemChecked(i, true);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多