我想将清单框中的选中项目提取到标签中

i want to fetch Checked items on a checklistbox into a label

提问人:Geko 提问时间:10/11/2023 最后编辑:Geko 更新时间:10/11/2023 访问量:38

问:

string acom = AcompList.CheckedItems.ToString();
            Label1.Text = (Pratotxt.Text + "\n" + Tamanhotxt.Text + "\n" + Obstxt.Text + "\n" + acom + "\n" + Mesatxt.Text + "\n" + Enderecotxt.Text);

但它在标签上显示以下文本:System.Windows.Forms.CheckedListBox+CheckedItemCollection

我用过

AcompList.CheckedItems.ToString();
 \\doesnt work
string acom = AcompList.GetSelected;
 \\ idk why i even used this one
string acom = AcompList.Items.Cast<string>; 
\\ gives CS0428 error

C# 字符串 ArrayList 清单框

评论

0赞 Ňɏssa Pøngjǣrdenlarp 10/11/2023
CheckedItemsitems 是项的集合。您需要迭代集合并打印每个项目。这里有很多很多的例子可以做到这一点。通过更多的研究,您可以学会使用 linq 将所选内容联接到一个逗号分隔的字符串中。
0赞 Geko 10/11/2023
@Ň ɏssaPøngjǣrdenlarp 我对这些概念完全陌生,从未听说过 Linq,几周前开始使用 C# ty

答:

0赞 User12345 10/11/2023 #1

像 Ňɏssa Pøngjǣrdenlarp 项目一样,项目是项目的集合。您应该像这样循环访问项目列表CheckedItems

    string checkedItemsText = "";
    
    foreach (object item in AcompList.CheckedItems) 
    //or CheckedIndices if you just want to concat string with checked=true
    { 
        checkedItemsText += item.ToString() + "\n";
    }
0赞 Karen Payne 10/11/2023 #2

下面是一个示例,其中项被添加到 Items 集合中数月。

通过项目加载

MonthsCheckedListBox.Items.AddRange(DateTimeFormatInfo.CurrentInfo.MonthNames[..^1].ToArray());

或 DataSource

MonthsCheckedListBox.DataSource = DateTimeFormatInfo.CurrentInfo.MonthNames[..^1].ToList();

语言扩展以获取选中的项目。请注意,这可以在没有扩展的情况下完成,但这可以保持代码干净。

public static class CheckedListBoxExtensions
{
    public static List<T> CheckedList<T>(this CheckedListBox sender)
        => sender.Items.Cast<T>()
            .Where((_, index) => sender.GetItemChecked(index))
            .Select(item => item)
            .ToList();
}

此处的分隔符为空格的用法,请根据需要更改。

Label1.Text = string.Join(" ", MonthsCheckedListBox.CheckedList<string>());

var results = string.Join(" ", MonthsCheckedListBox.CheckedList<string>());
if (string.IsNullOrWhiteSpace(results))
{
    Label1.Text = "No selection";
}
else
{
    Label1.Text = results;
}