ListBox.ObjectCollection.RemoveAt(Int32) 方法

定義

移除這個集合中位於指定索引處的項目。

public:
 virtual void RemoveAt(int index);
public void RemoveAt (int index);
abstract member RemoveAt : int -> unit
override this.RemoveAt : int -> unit
Public Sub RemoveAt (index As Integer)

參數

index
Int32

要移除之項目的以零為起始的索引。

實作

例外狀況

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

範例

下列程式碼範例示範如何使用 SelectedIndex 屬性搭配 TopIndex 屬性,將目前選取的專案移至 顯示區域中 ListBox 專案清單頂端。 此範例會進一步示範如何使用 類別的 System.Windows.Forms.ListBox.ObjectCollection 方法移除專案 RemoveAt ,以及如何使用 ClearSelected 方法清除所有專案選取專案。 程式碼會先將 中 ListBox 目前選取的專案移至清單頂端。 然後,程式碼會移除目前選取專案之前的所有專案,並清除 中的所有 ListBox 選取專案。 此範例會 ListBox 要求將包含專案的 加入表單中,而且目前已在 中 ListBox 選取專案。

private:
   void RemoveTopItems()
   {
      // Determine if the currently selected item in the ListBox 
      // is the item displayed at the top in the ListBox.
      if ( listBox1->TopIndex != listBox1->SelectedIndex )

      // Make the currently selected item the top item in the ListBox.
      listBox1->TopIndex = listBox1->SelectedIndex;

      // Remove all items before the top item in the ListBox.
      for ( int x = (listBox1->SelectedIndex - 1); x >= 0; x-- )
      {
         listBox1->Items->RemoveAt( x );
      }

      // Clear all selections in the ListBox.
      listBox1->ClearSelected();
   }
private void RemoveTopItems()
{
   // Determine if the currently selected item in the ListBox 
   // is the item displayed at the top in the ListBox.
   if (listBox1.TopIndex != listBox1.SelectedIndex)
      // Make the currently selected item the top item in the ListBox.
      listBox1.TopIndex = listBox1.SelectedIndex;

   // Remove all items before the top item in the ListBox.
   for (int x = (listBox1.SelectedIndex -1); x >= 0; x--)
   {
      listBox1.Items.RemoveAt(x);
   }

   // Clear all selections in the ListBox.
   listBox1.ClearSelected();
}
Private Sub RemoveTopItems()
   ' Determine if the currently selected item in the ListBox 
   ' is the item displayed at the top in the ListBox.
   If listBox1.TopIndex <> listBox1.SelectedIndex Then
      ' Make the currently selected item the top item in the ListBox.
      listBox1.TopIndex = listBox1.SelectedIndex
   End If
   ' Remove all items before the top item in the ListBox.
   Dim x As Integer
   For x = listBox1.SelectedIndex - 1 To 0 Step -1
      listBox1.Items.RemoveAt(x)
   Next x

   ' Clear all selections in the ListBox.
   listBox1.ClearSelected()
End Sub

備註

當您從清單中移除專案時,索引會變更清單中的後續專案。 已刪除已移除專案的所有資訊。 您可以使用這個方法來從清單中移除特定專案,方法是指定要從清單中移除的專案索引。 若要指定要移除的專案,而不是專案的索引,請使用 Remove 方法。 若要從清單中移除所有專案,請使用 Clear 方法。

適用於

另請參閱