簡體   English   中英

獲取列表框的選定索引(C#)

[英]getting selected index of listbox(c#)

我有一個SelectionBox設置為多個的ListBox 當我使用ListBox1.SelectedIndex檢查所選索引時,即使單擊某個項目,我也總是得到-1? 我希望能夠獲得列表框中多個選定項目的索引。

使用GetSelectedIndices()方法。

由於可以選擇一個以上的項目,因此必須獲得SelectedItems的集合。 遍歷它們。 每個項目都有索引屬性。

試試這個方法

ListBox.SelectedIndexCollection SelectedIndices { get; }

當您只允許選擇一個值時,將使用SelectedIndex方法。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM