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

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

  • Comments 3

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

 

Attachment: WebApplication2.zip
Leave a Comment
  • Please add 7 and 2 and type the answer here:
  • Post
  • how should we do it in a 3 layers app? we will never normally have the NorthwindEntities context in the presentation layer.

    thanks

  • My bet is ClassLib Project

  • I am unable to thank because words do not meet your right  

    Thank you

    Thank you

Page 1 of 1 (3 items)