如何:從 Windows Form 的 ComboBox、ListBox 或 CheckedListBox 控制項加入或移除項目
專案可以透過各種方式新增至 Windows Forms 下拉式方塊、清單方塊或核取方塊,因為這些控制項可以系結至各種資料來源。 不過,本主題示範最簡單的方法,而且不需要任何資料系結。 顯示的專案通常是字串;不過,可以使用任何物件。 控制項中顯示的文字是 物件 ToString
方法所傳回的值。
若要新增專案
使用
Add
類別的ObjectCollection
方法,將字串或物件新增至清單。 集合會使用Items
屬性來參考:ComboBox1.Items.Add("Tokyo")
comboBox1.Items.Add("Tokyo");
comboBox1->Items->Add("Tokyo");
- 或-
使用
Insert
方法,在清單中所需的點插入字串或物件:CheckedListBox1.Items.Insert(0, "Copenhagen")
checkedListBox1.Items.Insert(0, "Copenhagen");
checkedListBox1->Items->Insert(0, "Copenhagen");
- 或-
將整個陣列指派給
Items
集合: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)
System.Object[] ItemObject = new System.Object[10]; for (int i = 0; i <= 9; i++) { ItemObject[i] = "Item" + i; } listBox1.Items.AddRange(ItemObject);
Array<System::Object^>^ ItemObject = gcnew Array<System::Object^>(10); for (int i = 0; i <= 9; i++) { ItemObject[i] = String::Concat("Item", i.ToString()); } listBox1->Items->AddRange(ItemObject);
移除專案
Remove
呼叫 或RemoveAt
方法來刪除專案。Remove
有一個引數,指定要移除的專案。RemoveAt
移除具有指定索引編號的專案。' 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")
// 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");
// 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");
移除所有專案
Clear
呼叫 方法以移除集合中的所有專案:ListBox1.Items.Clear()
listBox1.Items.Clear();
listBox1->Items->Clear();
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將推出:在 2024 年,我們將隨著內容的意見反應機制逐步淘汰 GitHub 問題,並以新的意見反應系統來取代。 如需詳細資訊,請參閱提交並檢視相關的意見反應