In this article I will explain with an example, how to populate (bind) DataGridView using
Entity Framework in Windows Forms (WinForms) Application using C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Form Design
The following form consists of:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Linq;
VB.Net
Imports System.Data
Imports System.Linq
Populating DataGridView using Entity Framework with C# and VB.Net
Inside the
Form Load event handler, an object of
NorthwindEntities class is created and records from the
Customers Table are fetched using
Entity Framework and are assigned to the
DataSource property of the DataGridView control.
C#
private void Form1_Load(object sender, EventArgs e)
{
NorthwindEntities entities = new NorthwindEntities();
var customers = from p in entities.Customers
select new
{
CustomerId = p.CustomerID,
ContactName = p.ContactName,
Country = p.Country
};
dataGridView1.DataSource = customers.ToList();
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim entities As NorthwindEntities = New NorthwindEntities()
Dim customers = From p In entities.Customers _
Select New With {.CustomerId = p.CustomerID, _
.ContactName = p.ContactName, _
.Country = p.Country}
dataGridView1.DataSource = customers.ToList()
End Sub
Screenshot
Downloads