![](/img/trans.png)
[英]How to return items from a list according to their respective checked box in checkedlistbox C#?
[英]How to check a box in CheckedListBox while the items in the list are custom objects in a C# window form application?
我在c#中創建一個“導出到excel”的Windows窗體。 該類包含一個CheckedListBox和一個“全部選中”按鈕。 當單擊按鈕時,我要檢查列表中的所有項目,以防萬一沒有選中至少一個復選框,或者如果所有復選框都已選中,請取消選中所有復選框。
我添加了一個小麻煩,項目列表是自定義對象的列表(請參閱內部的私有類):“ 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);
}
}
問題是,即使未選中此復選框,以下行也將返回true:
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
與以下行類似的問題,如果checkAll為true,則不會選中任何復選框:
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
檢查過濾。
這意味着,過濾后的查詢始終返回空,並且查詢永遠不會到達“全部”。 這可以用下面的例子來證明。
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.