现在我有
String myString = listbox1.Text.ToString();
然而,这只返回第一项,即使我按下ctrl并选择所有项目。
感谢您的帮助
答案 0 :(得分:1)
你是对的,WebForms ListBox没有SelectedItems属性。但是,你可以做到
listBox.Items.OfType<ListItem>().Where(i => i.Selected);
这将为您提供您正在寻找的物品。
如果你不能使用LINQ,只需在listBox.Items上做一个foreach,并在选择项目时做你想做的任何事情。
答案 1 :(得分:1)
使用扩展方法,您可以这样做:
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}
用法:
var selected = listbox1.Items.GetSelectedItems();
现在你可以使用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());