[英]How to select all items in a Listbox and concatenate them in ASP.NET C# Webform?
Right now I have 现在我有
String myString = listbox1.Text.ToString();
However this only returns only the 1st item, even if I hit ctrl and select all of them. 但是,即使我按了ctrl并选择了所有这些项,它也仅返回第一项。
Thanks for any help 谢谢你的帮助
You are right, WebForms ListBox doesn't have the SelectedItems property. 是的,WebForms ListBox没有SelectedItems属性。 However, you can do
但是,你可以做
listBox.Items.OfType<ListItem>().Where(i => i.Selected);
That will give you the items you are looking for. 这将为您提供所需的物品。
If you can't use LINQ, just do a foreach over listBox.Items, and do whatever you want when the item is Selected. 如果您不能使用LINQ,则只需对listBox.Items进行一次foreach,然后在选中该项目时执行您想要的任何操作。
Using an extension method, you can do this: 使用扩展方法,您可以执行以下操作:
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}
Usage: 用法:
var selected = listbox1.Items.GetSelectedItems();
Now you can take the IEnumerable<ListItem>
and convert that to a string array, then finally make it into a single string separated by semicolons, like this: 现在,您可以使用
IEnumerable<ListItem>
并将其转换为字符串数组,然后最终使其成为由分号分隔的单个字符串,如下所示:
// Create list to hold the text of each list item
var selectedItemsList = new List<string>();
// Create list to hold the text of each list item
var selectedItemsList = selected.Select(listItem => listItem.Text).ToList();
// Build a string separated by comma
string selectedItemsSeparatedByComma = String.Join(",",
selectedItemsList.ToArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.