In this article I will explain with example, how to bind GridView control using Entity Framework in ASP.Net using C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Configuring and connecting Entity Framework to database
HTML Markup
The following HTML Markup consists of an ASP.Net GridView control with three BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="Customer Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Populating GridView control in ASP.Net
Inside the Page Load event handler, the Top 10 records from the Customers table are fetched using Entity Framework and assigned to the DataSource property of the GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (NORTHWINDEntities entities = new NORTHWINDEntities())
{
gvCustomers.DataSource = (from customer in entities.Customers.Take(10)
select customer).ToList();
gvCustomers.DataBind();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Using entities As NORTHWINDEntities = New NORTHWINDEntities()
gvCustomers.DataSource = (From customer In entities.Customers.Take(10) Select customer).ToList()
gvCustomers.DataBind()
End Using
End If
End Sub
Screenshot
Demo
Downloads