How to populate a ComboBox with data in C#
By FoxLearn 7/18/2024 3:45:13 AM 10.95K
Open your Visual Studio, then click 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 button.
How to populate a ComboBox with data in C#
To populate a ComboBox with data in C#, you typically need to follow these steps
Drag and drop Label, Combobox controls from Visual Studio toolbox onto your form designer, then you can layout your form as shown below.
You need the data that you want to populate the ComboBox with. This could be a collection of strings, objects, or any other data type you need.
I will create a City class to map data
public class City { public int ID { get; set; } public string Name { get; set; } }
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) { // Sample data - replace this with your own data source 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" }); // Assign data source to the ComboBox 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)); } } }
Assign the data source to the ComboBox's DataSource
property. This tells the ComboBox where to get its data from.
If your data source is a collection of objects, you need to specify which property of the objects should be displayed in the ComboBox. Set the DisplayMember
property to the name of this property.
If you want to associate each item in the ComboBox with a specific value, you can set the ValueMember
property to the name of the property in your objects that contains this value.
VIDEO TUTORIALS