How to: Add and Remove Items from a Windows Forms ComboBox



 Consider this window :




Create a class named Item :
 
class Item 
{
  private string itemName;
  public Item(string itemName) //Constructor
  {
    this.itemName = itemName;
  }
  public string ItemName
  {
    get { return itemName; }
  }
}
 
Now double click on SAVE button then write this code : 


private Item itemObject;
 
private void addButton_Click(object sender, EventArgs e)
{
 itemObject = new Item(itemNameTextBox.Text);
 itemComboBox.DisplayMember = “itemName”; //Show itemName in ComboBox
 itemComboBox.Items.Add(itemObject);
 MessageBox.Show(“Item has been added”);
}

Now we can run this code.After running this code take an item in text box and click SAVE button.Then in combo box we will see :
 



Now we want to delete this item from comboBox.Take a remove button just like this,







Now double click on Remove button then write this code :
 private void removeButton_Click(object sender, EventArgs e)
{
itemComboBox.Items.Remove(itemObject);
MessageBox.Show(“Item has been deleted”);
}



Now if we give input in text box which is “Pen” and then click remove button then item “pen” will be deleted.Just like this,



Now we can add and remove more than one element.Just write down the elements name in text box and click add button and show combo box.Then we will see the elements in combo box serially.And by clicking Remove button we can remove any item from combo box.

 

Leave a Reply