1

I have a CheckBoxList with some items in it and when a user clicks a button, I want the value of the checked text boxes to be added to a single string. I've looked all throughout here for an answer but most of them don't work or produce undesired results. Here is the code I have so far:

string selectedItems = CheckBoxList1.Items.???

Not sure where to go from here. Any help is appreciated!

1

2 Answers 2

8

You can use String.Join with LINQ like:

string selectedItems = String.Join(",",
    CheckBoxList1.Items.OfType<ListItem>().Where(r => r.Selected)
        .Select(r => r.Text));

This will give you a comma separated string of all selected items.

Sign up to request clarification or add additional context in comments.

7 Comments

is OfType thing is necessary here?
@EhsanSajjad, OfType or Cast to use LINQ otherwise it is just a ItemCollection and you can't use LINQ over it.
Items is not a collection in this case?
@EhsanSajjad, it is ItemCollection which implements IEnumerable and not IEnumerable<T>. Therefore you can't use LINQ over it.
it means if Type is not known we can't use LInq on it
|
1

Try this:

 var selected = string.Join(", ", CheckBoxList1.Items.Cast<ListItem>()
                         .Where(li => li.Selected).Select(x => x.Value).ToArray());

1 Comment

This will work assuming he wants the value instead of the text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.