如何检查框CheckedListBox而在列表中的项目是在C#窗口形式的应用程序自定义对象?

问题描述 投票:0回答:1

我创建的“导出到Excel”窗口在C#中形成。该类包含一个CheckedListBox和“检查所有”按钮。当按钮点击我要检查列表中的所有项目的情况下,至少有一个复选框没有被选中或取消所有的情况下,他们都已经选中的复选框。

enter image description here

我加了一个小麻烦,该项目的列表是自定义对象(见里面私有类)的列表:“ObjectToExport”级。

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

问题是,下面一行返回即使没有复选框被选中真:

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

与以下行类似的问题,如果checkAll是真实的,没有复选框被选中:

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

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

c# winforms checkedlistbox
1个回答
1
投票

你的问题就从这里开始。

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

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

你加入“ObjectToExport”的情况下,到FormsCheckedListBox,但同时过滤,你正在检查与CheckBox过滤。

这意味着,你的过滤查询总是返回空,查询永远不会达到全部。这可以用下面的例子来说明。

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

以上结果将是True,它绝不会打印出“内的所有”文本。这是与您查询的发生。

你可以找到如有复选框的使用检查

var ifAnyChecked = checkedListBox1.CheckedItems.Count !=0;

要改变状态,你可以做到以下几点。

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

   }
}
© www.soinside.com 2019 - 2024. All rights reserved.