代码之家  ›  专栏  ›  技术社区  ›  eomeroff

循环访问WinForms中的CheckedListBox?

  •  4
  • eomeroff  · 技术社区  · 15 年前

    如果我在win表单中选中了列表框,我会这样填写

    List<Tasks> tasks = db.GetAllTasks();
            foreach (var t in tasks)
                tasksCheckedListBox.Items.Add(t.Name);
    

    如何迭代taskscheckedlistbox.items并将某些复选框设置为选中?

    谢谢

    2 回复  |  直到 15 年前
        1
  •  3
  •   Lenny Sirivong    15 年前

    如果您想在添加项目后执行此操作,则有一个示例 on MSDN

    复制到这里:

    private void CheckEveryOther_Click(object sender, System.EventArgs e) {
        // Cycle through every item and check every other.
    
        // Set flag to true to know when this code is being executed. Used in the ItemCheck
        // event handler.
        insideCheckEveryOther = true;
    
        for (int i = 0; i < checkedListBox1.Items.Count; i++) {
            // For every other item in the list, set as checked.
            if ((i % 2) == 0) {
                // But for each other item that is to be checked, set as being in an
                // indeterminate checked state.
                if ((i % 4) == 0)
                    checkedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
                else
                    checkedListBox1.SetItemChecked(i, true);
            }
        }        
    
        insideCheckEveryOther = false;
    }
    
        2
  •  6
  •   Jake Pearson    15 年前

    add方法采用可选的ischecked参数。然后可以将对象以正确的状态添加到选中的列表框中。

    List<Tasks> tasks = db.GetAllTasks();
            foreach (var t in tasks)
                tasksCheckedListBox.Items.Add(t.Name, isChecked);
    

    或者,您可以在添加项目后更改其选中状态,如下所示:

    foreach(var task in tasks)
    {
        tasksCheckedListBox.SetItemChecked(clb.Items.IndexOf(task), isChecked);
    }