简体   繁体   English

如何选择列表框中的所有项目并在ASP.NET C#Webform中将它们串联起来?

[英]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.

相关问题 如何在C#asp.net网络表单中建立一对多列表框连接? - How to make a one to many and many to many listbox connection in C# asp.net webform? 遍历 ASP.NET WebForm C# 中的所有 DropDownList - Iterating Through All DropDownList In an ASP.NET WebForm C# 在ASP.NET Web表单中比较并从列表框中删除项目 - Compare & remove items from Listbox in asp.net webform 我正在尝试对 ASP.NET 网络表单中的一系列控件进行分组,并使用 c# 对所有控件进行计算 - I'm trying to group a series of controls in an ASP.NET webform and perform a calculation on all of them using c# 如何从占位符获取所有文本框? asp.net c#网络表格 - How to get all textbox from a placeholder? asp.net c# webform 如何在HtmlTextWriter asp.net c#webform中追加字符串 - how to append string in a HtmlTextWriter asp.net c# webform 使用ASP.NET和C#在ListBox中选择多个值 - Select multiple value in ListBox using ASP.NET and C# 如何使用C#在ASP.NET中一一获取列表框中的项目 - how to get the items in listbox one by one in asp.net using c# 在RadioButtonList中选择一个项目,如何从asp.net中的数据库获取到ListBox的项目列表c# - Selecting an item in the RadioButtonList, how to get a list of items to a ListBox from database in asp.net c# 如何将项目添加到ListBox或XML中的另一个控件? ASP.Net(C#) - How to add items to ListBox or another control from XML? ASP.Net(C#)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM