简体   繁体   中英

C# CheckBoxList checked items to string

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!

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM