Windows Forms: How to link Combobox with database values in C#

By FoxLearn 7/29/2017 4:13:16 PM   5.99K
How to Link/Fill Combobox with database values in C#

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

c# link combobox with database valueStep 2: Design your form as below

link combobox with database value in c#

Step 3: Create an Entity Framework Model, then select Category and Product table from Northwind database

entity framework c#

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 LinkComboboxWithDatabaseValue
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cboCategory_SelectionChangeCommitted(object sender, EventArgs e)
        {
            Category obj = cboCategory.SelectedItem as Category;
            if (obj != null)
            {
                using (NorthwindEntities db = new NorthwindEntities())
                {
                    //Get products by categoryid
                    productBindingSource.DataSource = db.Products.Where(p => p.CategoryID == obj.CategoryID).ToList();
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init data
            using (NorthwindEntities db = new NorthwindEntities())
            {
                categoryBindingSource.DataSource = db.Categories.ToList();
                Category obj = cboCategory.SelectedItem as Category;
                if (obj != null)
                    productBindingSource.DataSource = db.Products.Where(p => p.CategoryID == obj.CategoryID).ToList();
            }
        }
    }
}

VIDEO TUTORIALS