【问题标题】:Iterate through CheckedListBox in WinForms?遍历 WinForms 中的 CheckedListBox?
【发布时间】:2010-02-01 23:51:29
【问题描述】:

如果我在我这样填写的 Win 表单中选中了列表框

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

如何迭代 tasksCheckedListBox.Items 并将一些复选框设置为选中?

谢谢

【问题讨论】:

  • db.GetAllTask​​s() 返回的信息中是否包含该项是选中还是未选中?或者您是否在根据其他数据源或标准创建 ListBox 后确定是否应检查项目?
  • 我仅通过其名称确定其已检查属性 GetAllTask​​s() 方法不包含任何有关已检查的信息。
  • 因此,每个 Task 的 .Name 属性中的某些内容会告诉您是否已检查它:如果是这种情况,那么我认为您可以在下面的 Jake Pearson 的回答中调整该技术。然后,当然,您将不得不添加一些代码来解析字符串(我们必须假设 .Name 属性存在)以确定检查状态。在这样的问题中,恕我直言,最好尽可能多地提供有关您用来确定如何评估数据以设置参数的标准的信息。祝你好运!

标签: c# winforms iteration checkedlistbox


【解决方案1】:

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);
}

【讨论】:

    【解决方案2】:

    如果你想在添加项目之后再做,有一个例子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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2021-06-26
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多