【问题标题】:getting selected index of listbox(c#)获取列表框的选定索引(c#)
【发布时间】:2012-11-06 13:45:37
【问题描述】:

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

【问题讨论】:

  • 没人知道你在说什么 ListBox 类。迭代 Items 集合并使用项目的 Selected 属性。在 MSDN 库文章中查找 ListBox.SelectionMode 的示例代码

标签: c# asp.net .net webforms listbox


【解决方案1】:

使用GetSelectedIndices() 方法。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试试这个方法

      ListBox.SelectedIndexCollection SelectedIndices { get; }
      

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

      【讨论】:

      • 在 Webforms 中,它不是这个属性,而是 GetSelectedIndices() 方法。
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-19
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        相关资源
        最近更新 更多