ComboBox Part 1 - adding items to the combobox

The ComboBox object provides the same benefits as a list does but it has the ability to expand and contract saving a lot of space in your windows form application.

In the next Quick Example, I'll show you how to add a ComboBox to a Windows Form Application and how to add items in it in two different ways.

1- By passing a range of items (in a list)
2- Adding a specific item by clicking a Button.

  1. First, create a Windows Form Application Project

    2. Drag a ComboBox Object to your Window.

    3. Add some code:

     I created a List items to store some strings that will then be added at the Load event.
  List<string> items = new List<string>() { "1-Lucia", "2-Mauricio","3-Frank","4-Dog" };

   4. At the Load Event type this line.


 5.Then I added a button to show another way of adding items to the combobox
 In the Button Event put this line:

 comboBox1.Items.Add(comboBox1.Items.Count+1+"-Item Added by Button");


The full Code below (it is all commented)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ComboBoxTest
    public partial class Form1 : Form
        //creates and initialize a list with strings
        //(could contain any type of object)
        List<string> items = new List<string>() { "1-Lucia", "2-Mauricio", "3-Frank", "4-Dog" };
        public Form1()

        //The action takes part in the Load event, it could be a button or any other event.
        private void Form1_Load(object sender, EventArgs e)
            //here we load the combobox with the list
            //we set the selected to "1-Lucia", it also work with any kind of objects.(it depends on
            //what you put in the list.
            comboBox1.SelectedItem = "1-Lucia";

        private void button_add_Click(object sender, EventArgs e)
            //here we add an item to the combobox manually
            //"comboBox1.Items.Count+1" is just to show the apropiate index in the list
            //it calculates how many items are in the combobox and increments the value by 1
            comboBox1.Items.Add(comboBox1.Items.Count+1+"-Item Added by Button");



At this point the ComboBox contains the List.


After the add button was clicked. The combobox contains now a new item.

Part 2 will cover the remove method and other combobox specific properties.

See you in the next C# Quick Example.

1 comment:

  1. This comment has been removed by a blog administrator.


2 ads