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

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

but it's showing this text on the label: System.Windows.Forms.CheckedListBox+CheckedItemCollection

i used

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

2

There are 2 best solutions below

0
User12345 On

Like Ňɏssa Pøngjǣrdenlarp CheckedItems items is a collection of items. You should looping the list of items like this

    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 On

Here is an example where items are added to the Items collection for months.

Load via Items

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

Or DataSource

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

Language extension to get checked items. Note this can be done w/o an extension but this keeps your code clean.

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

Usage where the delimiter here is a space, change as you see fit.

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

Or

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