ListBox.GetSelected(Int32) 方法

定義

傳回值,指出是否選取指定的項目。

C#
public bool GetSelected(int index);

參數

index
Int32

項目之以零起始的索引,可用來判斷該項目是否選取。

傳回

如果目前在 ListBox 中選取指定的項目,則為 true,否則為 false

例外狀況

index 參數小於零,或者大於等於 Count 類別的 ListBox.ObjectCollection 屬性值。

範例

下列程式碼範例示範如何使用 GetSelected 方法來判斷 中 ListBox 選取的專案,以選取未選取的專案,並取消選取選取的專案。 此範例也會示範如何使用 SelectionMode 屬性讓 ListBox 擁有多個選取的專案,並使用 Sorted 屬性來示範如何自動排序專案中 ListBox 的專案。 這個範例要求 ListBox 已將名為 listBox1 的 ,加入至表單,而且 InitializeMyListBox 從表單的 事件呼叫 Load 範例中定義的 方法。

C#
private void InitializeMyListBox()
{
   // Add items to the ListBox.
   listBox1.Items.Add("A");
   listBox1.Items.Add("C");
   listBox1.Items.Add("E");
   listBox1.Items.Add("F");
   listBox1.Items.Add("G");
   listBox1.Items.Add("D");
   listBox1.Items.Add("B");

   // Sort all items added previously.
   listBox1.Sorted = true;

   // Set the SelectionMode to select multiple items.
   listBox1.SelectionMode = SelectionMode.MultiExtended;

   // Select three initial items from the list.
   listBox1.SetSelected(0,true);
   listBox1.SetSelected(2,true);
   listBox1.SetSelected(4,true);

   // Force the ListBox to scroll back to the top of the list.
   listBox1.TopIndex=0;
}

private void InvertMySelection()
{
   // Loop through all items the ListBox.
   for (int x = 0; x < listBox1.Items.Count; x++)
   {
      // Determine if the item is selected.
      if (listBox1.GetSelected(x))
         // Deselect all items that are selected.
         listBox1.SetSelected(x,false);      
      else
         // Select all items that are not selected.
         listBox1.SetSelected(x,true);
   }
   // Force the ListBox to scroll back to the top of the list.
   listBox1.TopIndex=0;
}

備註

您可以使用這個方法來快速判斷是否已選取指定的專案。 當選取多重選取 ListBox 範圍中的特定專案時,需要執行特定作業時,這個方法會很有用。

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10