Data binding in an ASP.Net application with Entity Framework

This is going to be the eighth post of a series of posts regarding ASP.Net and the Entity Framework and how we can use Entity Framework to access our datastore. You can find the first one here, the second one here , the third one here , the fourth one here, the fifth one here ,the sixth one here and the seventh one here.

I have a post regarding ASP.Net and EntityDataSource. You can read it here.I have 3 more posts on Profiling Entity Framework applications. You can have a look at them here, here and here.

In this post I will be looking into databinding and Entity Framework. I will give a hands on example. We will have a dropdown list that will bind to results of a query (results implement the IQueryable interface). Then as the user makes his selection from the dropdown list the filtered results from another query (results implement the IQueryable interface) will bind to a Gridview control.

I assume that you have access to a version of SQL Server.If you do not, you can download and install the free SQL Server Express edition from here. 

In this post (step 9) you will find a T-SQL script that will create the database objects of the CompanyEmployees database.Before that you execute the T-SQL script you must create in the Query window the CompanyEmployees database yourself. You can download the companiesemployeesinsertt.zip to insert data into the tables.

1) Launch Visual Studio 2010 (express edition will work fine). Create an empty ASP.Net web site from the available templates and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your website,a web form.Leave the default name. Add a dropdownlist control on the form. Add a Gridview control on the form. Leave the default names.

3) Add a new project to your solution, a class library project.Remove the class1.cs file from the project. 

4) Add a new ADO.Net Entity Data model to the class library project. Choose a suitable name for it, e.g CompanyEmployees.edmx.

5) Then the Wizard pops up. Choose "Generate from Database" option and finish the steps of the wizard by selecting only the tables (Companies,Employees) to be included in the model. Now you have your model ready with all the entities and the generated code.

6) Now we want to populate the dropdown list control with the names of the companies.Set the AutoPostBack property of the dropdown list control to True.

AutoPostBack="True" 

In the Page_Load event handling routine of the default.aspx page type ,

try
  {
  if (!IsPostBack)
  {
  using (var ctx = new CompanyEmployeesEntities())
  {
               
  var companies = from comp in ctx.Companies
      where comp.CompanyName.StartsWith("Ad")
      orderby comp.CompanyName
      select new { comp.CompanyID, comp.CompanyName };

     DropDownList1.DataValueField = "CompanyID";
     DropDownList1.DataTextField = "CompanyName";
     DropDownList1.DataSource = companies;
     DataBind();


     }

   }
 }

        
catch (Exception ex)
 {
            
Response.Write(ex.Message);
 }

 

7) Run your application and see the dropdown list control populated with the companies names that start with "Ad".

The companies returns an anonymous type of something.Remember that the var keyword declares and initialises anonymous types.

In my case it returns (the anonymous type is)

{System.Data.Objects.ObjectQuery<<>f__AnonymousType0<int,string>>}

Now we see that this is an ObjectQuery<T> that implements the IListSource interface. Through that interface a binding list is obtained that our dropdown list control knows how to talk to.

8) In the DropDownList_SelectedIndexChanged event handling routine type,

  {
        try 
{         
using (var ctx = new CompanyEmployeesEntities())
            {
                int compID;
                if(int.TryParse(DropDownList1.SelectedValue,out compID))
                {
                var empcomp = from emp in ctx.Employees
                              where emp.CompanyID == compID
                              orderby emp.EmpFirstName
                              select new {emp.EmpFirstName,emp.EmpLastName };


                GridView1.DataSource = empcomp;
                GridView1.DataBind();


                }
            }

}
catch (Exception ex)
{

 Response.Write(ex.Message);
}
         
    }

 

This is a very easy bit of code to follow. I create again the ObjectContext object and the I get the CompanyID for the selected company name and store it on the compID variable.

Then I construct my query and get only the first and last names of the employee(s) from the Employees table where the CompanyID (foreign key) matches the value in the compID variable.

Then databinding to the Gridview is a piece of cake.

9) Run your application. Make sure there are no compile or run time errors. Select a company name from the dropdown list control and see the first and last name of that Employee(s) belonging to that company displayed on the Gridview control. Set some breakpoints on the code and step into the code.

Drop me an email if you want the source code.

Hope it helps!!!!

1 Comment

Comments have been disabled for this content.