简体   繁体   English

C#CheckBoxList将已检查的项目转换为字符串

[英]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. 我有一个包含一些项目的CheckBoxList ,当用户单击一个按钮时,我希望将选中的文本框的值添加到单个字符串中。 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: 您可以将LINQ与String.Join结合使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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