ADO.NET Entity Framework 4.0 : DataBinding with Windows Forms

ADO.NET Entity Framework 4.0 : DataBinding with Windows Forms

  • Comments 1

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!!!

Attachment: WindowsFormsApplication1.zip
Leave a Comment
  • Please add 5 and 8 and type the answer here:
  • Post
  • This is working fine. but the datagrid not allows to insert/update etc. what is to be done?

    Thanks.

Page 1 of 1 (1 items)