【问题标题】:Getting all selected values from an ASP ListBox从 ASP 列表框中获取所有选定的值
【发布时间】:2010-12-07 20:23:26
【问题描述】:

我有一个 ASP 列表框,它的 SelectionMode 设置为“Multiple”。有什么方法可以检索所有选定的元素,而不仅仅是最后一个?

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

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

【问题讨论】:

    标签: c# asp.net webforms listbox


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用列表框的GetSelectedIndices方法

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

      【讨论】:

        【解决方案3】:

        尝试使用我使用 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
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-11
          • 2016-10-14
          • 1970-01-01
          • 2011-08-23
          • 2013-10-25
          • 1970-01-01
          • 1970-01-01
          • 2016-11-06
          相关资源
          最近更新 更多