Windows Forms: How to populate a ComboBox with data in C#
By FoxLearn 7/26/2017 9:05:57 PM 10.69K
How to populate a ComboBox with data in C#
Step 1: 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
Step 2: Design your form as below
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
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024