由於 Windows Form 下拉式方塊、清單方塊或選取的清單方塊可繫結至不同的資料來源,因此您可以使用多種方法將項目加入這些控制項。不過,本主題將示範最簡單的方法並在假設無資料繫結 (Data Binding) 的前提下進行。顯示的項目通常是字串;不過,您也可使用任何物件。顯示在控制項中的文字為物件的 ToString 方法所傳回的值。
若要加入項目
- 使用 ObjectCollection 類別的 Add 方法,將字串或物件加入清單。集合是使用 Items 屬性來參考的:
- ' Visual Basic
- ComboBox1.Items.Add("Tokyo")
- // C#
- comboBox1.Items.Add("Tokyo");
- // C++
- comboBox1->Items->Add(S"Tokyo");
- 或 -
- 使用 Insert 方法,在清單中的目標點插入字串或物件:
- ' Visual Basic
- CheckedListBox1.Items.Insert(0, "Copenhagen")
- // C#
- checkedListBox1.Items.Insert(0, "Copenhagen");
- // C++
- checkedListBox1->Items->Insert(0, S"Copenhagen");
- 或 -
- 將整個陣列指派給 Items 集合:
- ' Visual Basic
- Dim ItemObject(9) As System.Object
- Dim i As Integer
- For i = 0 To 9
- ItemObject(i) = "Item" & i
- Next i
- ListBox1.Items.AddRange(ItemObject)
- // C#
- System.Object[] ItemObject = new System.Object[10];
- for (int i = 0; i <= 9; i++)
- {
- ItemObject[i] = "Item" + i;
- }
- listBox1.Items.AddRange(ItemObject);
- // C++
- System::Object* ItemObject[] = new System::Object*[10];
- for (int i = 0; i <= 9; i++)
- {
- ItemObject[i] = String::Concat(S"Item", i.ToString());
- }
- listBox1->Items->AddRange(ItemObject);
若要移除項目
- 呼叫 Remove 或 RemoveAt 方法來刪除項目。
Remove 有一個會指定要移除項目的引數。RemoveAt 會移除指定索引編號的項目。
- ' Visual Basic
- ' To remove item with index 0:
- ComboBox1.Items.RemoveAt(0)
- ' To remove currently selected item:
- ComboBox1.Items.Remove(ComboBox1.SelectedItem)
- ' To remove "Tokyo" item:
- ComboBox1.Items.Remove("Tokyo")
- // C#
- // To remove item with index 0:
- comboBox1.Items.RemoveAt(0);
- // To remove currently selected item:
- comboBox1.Items.Remove(comboBox1.SelectedItem);
- // To remove "Tokyo" item:
- comboBox1.Items.Remove("Tokyo");
- // C++
- // To remove item with index 0:
- comboBox1->Items->RemoveAt(0);
- // To remove currently selected item:
- comboBox1->Items->Remove(comboBox1->SelectedItem);
- // To remove "Tokyo" item:
- comboBox1->Items->Remove(S"Tokyo");
若要移除所有的項目
- 呼叫 Clear 方法,從集合移除所有項目:
- ' Visual Basic
- ListBox1.Items.Clear()
- // C#
- listBox1.Items.Clear();
- // C++
- listBox1->Items->Clear();