2012-11-06 21 views
0

我有一個ListBox SelectionMode設置爲多個。當我使用ListBox1.SelectedIndex檢查選定的索引時,即使點擊某個項目,我也總是得到-1?我希望能夠獲得列表框中多個選定項目的索引。獲取列表框的選定索引(c#)

+0

沒有人知道你在說什麼ListBox類。迭代Items集合並使用該項目的Selected屬性。在ListBox.SelectionMode –

+0

的MSDN Library文章中查找示例代碼請查看[ListBox.GetSelectedIndices](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listbox.getselectedindices.aspx ) –

回答

3

使用GetSelectedIndices()方法。

1

試試這個方法,當你允許選擇只有一個值

ListBox.SelectedIndexCollection SelectedIndices { get; } 

SelectedIndex的方法被使用。

+0

在Webforms中,它不是這個屬性,而是GetSelectedIndices()方法。 – Rik

2

由於可以選擇多個項目,您必須獲取SelectedItems的集合。循環他們。每個項目都有索引屬性。

0

嘗試類似這樣的事情。您將使用此代碼在一個字符串中獲取所有選定的索引。

int length = this.ListBox1.Items.Count; 
    StringBuilder b = new StringBuilder(); 
    for (int i = 0 ; i < length; i++) 
     { 
     if (this.ListBox1.Items[ i ] != null && this.ListBox1.Items[ i ].Selected) 
       { 
     b.Append(this.ListBox1.Items[ i ].Selected); 
     b.Append(","); 
      } 
    } 
    if (b.Length > 0) 
     { 
     b.Length = b.Length - 1; 
    } 
    return b.ToString();