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.

image

 

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

DropDownList

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

            onselectedindexchanged="DropDownList1_SelectedIndexChanged">

        </asp:DropDownList>

GridView

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

        </asp:GridView>

 

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";

        DropDownList1.DataBind();

 

   }

}

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();

    GridView1.DataBind();

I will follow with WindowsForms and WPF way to implement.

Namoskar!!!

WebApplication2.zip

Comments

  • Anonymous
    March 02, 2011
    how should we do it in a 3 layers app? we will never normally have the NorthwindEntities context in the presentation layer. thanks

  • Anonymous
    March 13, 2011
    My bet is ClassLib Project

  • Anonymous
    February 14, 2013
    I am unable to thank because words do not meet your right   Thank you Thank you