從 Windows Form ComboBox、ListBox 或 CheckedListBox 控制項加入或移除項目

由於 Windows Form 下拉式方塊、清單方塊或選取的清單方塊可繫結至不同的資料來源,因此您可以使用多種方法將項目加入這些控制項。不過,本主題將示範最簡單的方法並在假設無資料繫結 (Data Binding) 的前提下進行。顯示的項目通常是字串;不過,您也可使用任何物件。顯示在控制項中的文字為物件的 ToString 方法所傳回的值。

若要加入項目

  • 使用 ObjectCollection 類別的 Add 方法,將字串或物件加入清單。集合是使用 Items 屬性來參考的:
    1. ' Visual Basic
    2. ComboBox1.Items.Add("Tokyo")
    3.  
    4. // C#
    5. comboBox1.Items.Add("Tokyo");
    6.  
    7. // C++
    8. comboBox1->Items->Add(S"Tokyo");

    - 或 -

  • 使用 Insert 方法,在清單中的目標點插入字串或物件:
    1. ' Visual Basic
    2. CheckedListBox1.Items.Insert(0"Copenhagen")
    3.  
    4. // C#
    5. checkedListBox1.Items.Insert(0"Copenhagen");
    6.  
    7. // C++
    8. checkedListBox1->Items->Insert(0, S"Copenhagen");

    - 或 -

  • 將整個陣列指派給 Items 集合:
    1. ' Visual Basic
    2. Dim ItemObject(9) As System.Object
    3. Dim i As Integer
    4.    For i = 0 To 9
    5.    ItemObject(i) = "Item" & i
    6. Next i
    7. ListBox1.Items.AddRange(ItemObject)
    8.  
    9. // C#
    10. System.Object[] ItemObject = new System.Object[10];
    11. for (int i = 0; i <= 9; i++)
    12. {
    13.    ItemObject[i] = "Item" + i;
    14. }
    15. listBox1.Items.AddRange(ItemObject);
    16.  
    17. // C++
    18. System::Object* ItemObject[] = new System::Object*[10];
    19. for (int i = 0; i <= 9; i++)
    20. {
    21.    ItemObject[i] = String::Concat(S"Item", i.ToString());
    22. }
    23. listBox1->Items->AddRange(ItemObject);

若要移除項目

  • 呼叫 Remove 或 RemoveAt 方法來刪除項目。

    Remove 有一個會指定要移除項目的引數。RemoveAt 會移除指定索引編號的項目。

    1. ' Visual Basic
    2. ' To remove item with index 0:
    3. ComboBox1.Items.RemoveAt(0)
    4. ' To remove currently selected item:
    5. ComboBox1.Items.Remove(ComboBox1.SelectedItem)
    6. ' To remove "Tokyo" item:
    7. ComboBox1.Items.Remove("Tokyo")
    8.  
    9. // C#
    10. // To remove item with index 0:
    11. comboBox1.Items.RemoveAt(0);
    12. // To remove currently selected item:
    13. comboBox1.Items.Remove(comboBox1.SelectedItem);
    14. // To remove "Tokyo" item:
    15. comboBox1.Items.Remove("Tokyo");
    16.  
    17. // C++
    18. // To remove item with index 0:
    19. comboBox1->Items->RemoveAt(0);
    20. // To remove currently selected item:
    21. comboBox1->Items->Remove(comboBox1->SelectedItem);
    22. // To remove "Tokyo" item:
    23. comboBox1->Items->Remove(S"Tokyo");

若要移除所有的項目

  • 呼叫 Clear 方法,從集合移除所有項目:
    1. ' Visual Basic
    2. ListBox1.Items.Clear()
    3.  
    4. // C#
    5. listBox1.Items.Clear();
    6.  
    7. // C++
    8. listBox1->Items->Clear();
原文地址:https://www.cnblogs.com/ArRan/p/2653754.html