-->

Saturday, June 7, 2014

How to Bind Gridview using Entity Framework in ASP.NET

How to Bind Gridview using Entity Framework in ASP.NET

In our previous article, we have already learned that how to bind gridview using ado.net. Today we will learn simplest technique to bind gridview using entity framework. Lets start to bind.
Step-1 : Add a Course class with some attributes like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for course
/// </summary>
public class course
{
    public int ID { get; set; }
    public string cname { get; set; }
    public string ccode { get; set; }

}
In this code ID is the primary key of the table. Learn How to make primary key in entity framework.
Step-2 : Add a DataContext class for creating database with some table like.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for DataContext
/// </summary>
public class DataContext : DbContext
{
public DataContext():base ("connection1")
{
//
// TODO: Add constructor logic here
//
}
  
    public DbSet<course> courses { get; set; }
}

DataContext class inherit from DbContext class which is inside in System.Data.Entity namespace. Learn How to download it
Here we pass ConnectionString in base class constructor as a parameter. Also add Course table in DataContext using DbSet. 

Step-3 : Add a new webform, which named as "getItem.aspx". Also add a gridView control onit from toolBox.
Step-4 : Add this code in codebehind page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class getitem : System.Web.UI.Page
{
    DataContext dc = new DataContext();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            bindgrid();
        }
    }

    private void bindgrid()
    {
        var item = from d in dc.courses
                   select d;
        GridView1.DataSource = item.ToList();
        GridView1.DataBind();
        
    }
}

Code Generate the following output

How to Bind Gridview using Entity Framework in ASP.NET

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved