C# 从 ASP 列表框中获取所有选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1586078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:05:24  来源:igfitidea点击:

Getting all selected values from an ASP ListBox

c#asp.netlistbox

提问by Evan Fosmark

I have an ASP ListBox that has the SelectionMode set to "Multiple". Is there any way of retreiving ALL selected elements and not just the last one?

我有一个 ASP ListBox,它的 SelectionMode 设置为“Multiple”。有没有办法检索所有选定的元素而不仅仅是最后一个?

<asp:ListBox ID="lstCart" runat="server" Height="135px" Width="267px" SelectionMode="Multiple"></asp:ListBox>

Using lstCart.SelectedIndexjust returns the last element (as expected). Is there something that will give me all selected?

使用lstCart.SelectedIndex只返回最后一个元素(如预期)。有什么东西可以让我全部选择吗?

This is for a web form.

这是用于 Web 表单。

采纳答案by Ahmad Mageed

You can use the ListBox.GetSelectedIndices methodand loop over the results, then access each one via the items collection. Alternately, you can loop through all the items and check their Selected property.

您可以使用ListBox.GetSelectedIndices 方法并遍历结果,然后通过 items 集合访问每个结果。或者,您可以遍历所有项目并检查它们的Selected 属性

// GetSelectedIndices
foreach (int i in ListBox1.GetSelectedIndices())
{
    // ListBox1.Items[i] ...
}

// Items collection
foreach (ListItem item in ListBox1.Items)
{
    if (item.Selected)
    {
        // item ...
    }
}

// LINQ over Items collection (must cast Items)
var query = from ListItem item in ListBox1.Items where item.Selected select item;
foreach (ListItem item in query)
{
    // item ...
}

// LINQ lambda syntax
var query = ListBox1.Items.Cast<ListItem>().Where(item => item.Selected);

回答by Niloofar

use GetSelectedIndices method of listbox

使用列表框的 GetSelectedIndices 方法

  List<int> selecteds = listbox_cities.GetSelectedIndices().ToList();

        for (int i=0;i<selecteds.Count;i++)
        {
            ListItem l = listbox_cities.Items[selecteds[i]];
        }

回答by V1NNY

try using this code I created using VB.NET :

尝试使用我使用 VB.NET 创建的这段代码:

Public Shared Function getSelectedValuesFromListBox(ByVal objListBox As ListBox) As String
    Dim listOfIndices As List(Of Integer) = objListBox.GetSelectedIndices().ToList()
    Dim values As String = String.Empty

    For Each indice As Integer In listOfIndices
        values &= "," & objListBox.Items(indice).Value
    Next indice
    If Not String.IsNullOrEmpty(values) Then
        values = values.Substring(1)
    End If
    Return values
End Function

I hope it helps.

我希望它有帮助。