获取列表框的选定索引(c#)

获取列表框的选定索引(c#),c#,asp.net,.net,webforms,listbox,C#,Asp.net,.net,Webforms,Listbox,我有一个列表框,SelectionMode设置为multiple。当我使用ListBox1.SelectedIndex检查所选索引时,即使单击某个项目,我也总是得到-1??我希望能够获取列表框中多个选定项目的索引。尝试此方法 ListBox.SelectedIndexCollection SelectedIndices { get; } 当您只允许选择一个值时,将使用SelectedIndex方法。使用GetSelectedDices()方法。由于可以选择多个项目,因此您必须获得Selecte

我有一个
列表框
,SelectionMode设置为multiple。当我使用
ListBox1.SelectedIndex
检查所选索引时,即使单击某个项目,我也总是得到-1??我希望能够获取列表框中多个选定项目的索引。

尝试此方法

ListBox.SelectedIndexCollection SelectedIndices { get; }

当您只允许选择一个值时,将使用SelectedIndex方法。

使用
GetSelectedDices()
方法。

由于可以选择多个项目,因此您必须获得SelectedItems的集合。循环通过它们。每个项目都有索引属性。

试试这样的方法。使用此代码,您将在一个字符串中获得所有选定的索引

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();
int length=this.ListBox1.Items.Count;
StringBuilder b=新的StringBuilder();
for(int i=0;i0)
{
b、 长度=b.长度-1;
}
返回b.ToString();

在Webforms中,不是这个属性,而是GetSelectedIndices()方法。没有人知道您在谈论什么样的ListBox类。迭代Items集合并使用该项的Selected属性。在MSDN库文章中查找ListBox.SelectionMode的示例代码请查看