Windows Forms: How to populate a ComboBox with data in C#

How to populate a ComboBox with data in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PopulateComboboxWithData" and then click OK

c# populate comboboxStep 2: Design your form as below

c# populate combobox with data

Step 3: Create a City class to map data

public class City
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Step 4: Add code to handle your form as below

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

namespace PopulateComboboxWithData
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init data
            List<City> list = new List<City>();
            list.Add(new City() { ID = 1, Name = "New York" });
            list.Add(new City() { ID = 2, Name = "Los Angeles" });
            list.Add(new City() { ID = 3, Name = "Chicago" });
            list.Add(new City() { ID = 4, Name = "Houston" });
            list.Add(new City() { ID = 5, Name = "Philadelphia" });
            cboCity.DataSource = list;
            cboCity.ValueMember = "ID";
            cboCity.DisplayMember = "Name";
        }

        private void cboCity_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //Select an object from combobox
            City obj = cboCity.SelectedItem as City;
            if (obj != null)
                MessageBox.Show(string.Format("city id = {0}, name = {1}", obj.ID, obj.Name, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information));
        }
    }
}

VIDEO TUTORIALS