次の方法で共有


方法: Windows フォームのコンボ ボックス、リスト ボックス、または CheckedListBox コントロールから項目を追加および削除する

これらのコントロールはさまざまなデータ ソースにバインドできるため、アイテムはさまざまな方法で Windows フォームのコンボ ボックス、リスト ボックス、またはチェック リスト ボックスに追加できます。 ただし、このトピックでは最も簡単な方法について説明します。データ バインディングは必要ありません。 通常、表示される項目は文字列です。ただし、任意のオブジェクトを使用できます。 コントロールに表示されるテキストは、オブジェクトの ToString メソッドによって返される値です。

アイテムを追加するには

  1. Add クラスの ObjectCollection メソッドを使用して、文字列またはオブジェクトをリストに追加します。 コレクションは、Items プロパティを使用して参照されます。

    ComboBox1.Items.Add("Tokyo")
    
    comboBox1.Items.Add("Tokyo");
    
    comboBox1->Items->Add("Tokyo");
    
    • または
  2. Insert メソッドを使用して、リスト内の目的の位置に文字列またはオブジェクトを挿入します。

    CheckedListBox1.Items.Insert(0, "Copenhagen")
    
    checkedListBox1.Items.Insert(0, "Copenhagen");
    
    checkedListBox1->Items->Insert(0, "Copenhagen");
    
    • または
  3. 配列全体を 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);
    

アイテムを削除するには

  1. アイテムを削除するには、Remove または RemoveAt メソッドを呼び出します。

    Remove には、削除する項目を指定する 1 つの引数があります。 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");
    

すべてのアイテムを削除するには

  1. Clear メソッドを呼び出して、コレクションからすべての項目を削除します。

    ListBox1.Items.Clear()
    
    listBox1.Items.Clear();
    
    listBox1->Items->Clear();
    

こちらも参照ください