2009-10-18 73 views
17

我有一個ASP ListBox,其SelectionMode設置爲「Multiple」。是否有任何方法來檢索所有選定的元素,而不僅僅是最後一個?從ASP列表框中獲取所有選定的值

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

使用lstCart.SelectedIndex只是返回最後一個元素(如預期的那樣)。有什麼東西會給我所有選擇的?

這是一個web表單。

回答

50

您可以使用ListBox.GetSelectedIndices method並遍歷結果,然後通過items集合訪問每個結果。或者,您可以遍歷所有項目並檢查其Selected property。使用VB.NET使用此代碼,我創建列表框

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

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

謝謝。我用它給你的第二個解決方案工作。 – 2009-10-18 21:47:06

+0

沒有問題!我添加了代碼以顯示不同的方法。如果您決定使用LINQ,則需要投射Items集合。 – 2009-10-18 21:59:50

+1

LINQ lamba規則。謝謝您的幫助。 – 2015-12-28 13:29:57

3

使用GetSelectedIndices方法:

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 

我希望它能幫助。

0

試試

// 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); 
相關問題