ADO.NET Entity Framework 4.0 : DataBinding with Windows Forms

This post is to give an idea on how easily we can bind and create master details display in Windows Forms Application.

 

Here I am using Northwind sample database and using Category and Products tables. These two tables are connected with each other through CategoryId. We will create a model using these two tables. Please ensure that you check the Foreign Key checkbox while selecting table in the EF4 model creation wizard.

image

Now, in the Forms1 add two controls. Combo Box with id comboBox1 and Data Grid View with id dataGridView1.

Add the below code

private void Form1_Load(object sender, EventArgs e)

{

    using (var ctx = new NorthwindEntities())

    {

        comboBox1.DataSource = ctx.Categories.ToList();

        comboBox1.ValueMember = "CategoryID";

        comboBox1.DisplayMember = "CategoryName";

    }

}

And

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

{

    int iCatID = 0;

    try

    {

        iCatID = (int)comboBox1.SelectedValue;

    }

    catch { }

    if(iCatID > 0)

    {

        using (var ctx = new NorthwindEntities())

        {

            var q = from p in ctx.Products

                    where p.CategoryID == iCatID

                    select p;

            dataGridView1.DataSource = q.ToList();

        }

    }

}

Namoskar!!!

WindowsFormsApplication1.zip