可以通过多种方式将项添加到 Windows 窗体组合框、列表框或选中列表框,因为这些控件可以绑定到各种数据源。 但是,本主题演示了最简单的方法,无需数据绑定。 显示的项通常是字符串;但是,可以使用任何对象。 控件中显示的文本是对象 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();