2012-11-06 64 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();