How to populate ComboBox with data from Database in C#

By FoxLearn 11/19/2024 1:59:52 PM   7.27K
To populate a ComboBox with data from a database in a C# Windows Forms application using Entity Framework, follow these steps.

How to populate ComboBox with data from Database in C#?

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

Drag and drop Label, TextBox, Combobox controls from Toolbox onto your form designer, then design your form as below.

c# link combobox with database value

You can populate a ComboBox in C# by querying the database through Entity Framework and setting the ComboBox's DataSource property.

Create an EF Model, then add a category table form the Northwind database to your Entity Framework Model.

entity framework model c#

In the Form_Load event or a method, you can retrieve data from the database using Entity Framework and then bind it to the ComboBox.

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        //Load category data
        using (NorthwindEntities db = new NorthwindEntities())
        {
            cboCategory.DataSource = db.Categories.ToList();
            cboCategory.ValueMember = "CategoryID";
            cboCategory.DisplayMember = "CategoryName";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The ToList() method fetches all rows from the Categories table and converts them into a list. This list will then be assigned to the DataSource property of the ComboBox.

Setting DisplayMember and ValueMember:

  • DisplayMember: This tells the ComboBox what property of each object in the list to display.
  • ValueMember: This specifies the property of each object in the list to use as the value when an item is selected.

Once the ComboBox is populated, you can access the selected value using SelectedValue, and the display text using SelectedItem or Text.

For example, to get the selected category's ID:

int selectedCategoryId = (int)cboCategory.SelectedValue;

If you want to perform an action when the selected item in the ComboBox changes, you can handle the SelectionChangeCommitted event:

private void cboCategory_SelectionChangeCommitted(object sender, EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    // Get the selected category    
    Category obj = cboCategory.SelectedItem as Category;
    if (obj != null)
    {
        // Update data to textbox
        txtCategoryID.Text = obj.CategoryID.ToString();
        txtCategoryName.Text = obj.CategoryName;
        txtDescription.Text = obj.Description;
    }
    Cursor.Current = Cursors.Default;
}

This is the basic way to populate a ComboBox from a database using Entity Framework in C#.

VIDEO TUTORIAL