当列表中的项目是 C# window 表单应用程序中的自定义对象时,如何选中 CheckedListBox 中的框?

How to check a box in CheckedListBox while the items in the list are custom objects in a C# window form application?

我正在用 C# 创建一个 "export to excel" windows 表单。 class 包含一个 CheckedListBox 和一个 "check all" 按钮。 单击按钮时,我想检查列表中的所有项目,以防至少有一个复选框未选中,或者取消选中所有复选框,以防它们都已被选中。

我加了个小复杂,items的列表是自定义对象的列表(见privateclass里面):"ObjectToExport" class.

public partial class ExcelCustomExportForm : Form
{
    private class ObjectToExport 
    {
        private readonly IExcelExportable _form;
        public ObjectToExport(IExcelExportable form)
        {
            _form = form;
        }
        public override string ToString()
        {
            return $"{_form.FormName} ({_form.CreatedDate.ToShortDateString()} {_form.CreatedDate.ToShortTimeString()})";
        }
    }

    // each form in the list contains a gridview which will be exported to excel
    public ExcelCustomExportForm(List<IExcelExportable> forms)
    {
        InitializeComponent();
        Init(forms);
    }

    private void Init(List<IExcelExportable> forms)
    {
        foreach (IExcelExportable form in forms)
        {
            // Checked List Box creation
            FormsCheckedListBox.Items.Add(new ObjectToExport(form));
        }
    }

    private void CheckAllButton_Click(object sender, EventArgs e)
    {
        // checking if all the items in the list are checked
        var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
        CheckItems(!isAllChecked); 
    }

    private void CheckItems(bool checkAll)
    {
        if (checkAll)
        {
            CheckAllButton.Text = "Uncheck All";
        }
        else
        {
            CheckAllButton.Text = "Check All";
        }

        FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);
    }
}

问题是以下行 returns 即使未选中复选框也是如此:

var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);

与下一行类似的问题,如果 checkAll 为真,则不会选中任何复选框:

FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);

修复这两行代码的正确方法是什么?

你的问题从这里开始。

FormsCheckedListBox.Items.Add(new ObjectToExport(form));

var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);

您正在将“ObjectToExport”的实例添加到 FormsCheckedListBox,但在筛选时,您正在使用 CheckBox.

检查筛选

这意味着,您过滤的查询始终 return 为空,并且查询永远不会到达全部。这可以用下面的例子来证明。

var list = new [] { 1,2,3,4};
var result = list.OfType<string>().All(x=> {Console.WriteLine("Inside All"); return false;});

上面的结果将是 True,它永远不会打印 "Inside All" 文本。这就是您的查询所发生的情况。

您可以使用

查看是否选中了任何复选框
var ifAnyChecked = checkedListBox1.CheckedItems.Count !=0;

要更改状态,您可以执行以下操作。

for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
   { 
         // Do something

   }
}