ADO.NET Entity Framework 4.0 : DataBinding with ASP.NET

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

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.



Then in WebForm1.aspx page add two controls with following html


<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server"




<asp:GridView ID="GridView1" runat="server">



Add the code to the Page_Load,

if (!Page.IsPostBack)


    using (var ctx = new NorthwindEntities())


        DropDownList1.DataSource = ctx.Categories;


        DropDownList1.DataTextField = "CategoryName";

        DropDownList1.DataValueField = "CategoryID";





And to DropDownList1_SelectedIndexChanged

using (var ctx1 = new NorthwindEntities())


    int cid = (int.Parse(DropDownList1.SelectedValue));

    GridView1.DataSource = (from p in ctx1.Products

                            where p.CategoryID == cid

                            select p).ToList();


I will follow with WindowsForms and WPF way to implement.