Display Data In DataGridView Using Entity Framework

Create Entity framework file

Go to Visual Studio and create Windows Forms Application and click OK as shown in Fig 1.

new

Go to Solution Explorer, select the solution click with right mouse button and then click on Add. Click on New Item as in the following figure Fig:2.

solution

Select Data from Visual C# ItemS in installed template. Select ADO .NET Entity Data Model, type the model name within parenthesis Model1.edmx, click on Add as shown in Fig:3,

Add

Select Generate from database option click on next, then again next as in the following figure 4,

database

Click on New Connection type the server name select the radio button and use the windows authentication (also we can use SQL Server authentication). Select the database name within parenthesis and check the Save entity connection settings in App.Config as, click on Finish as in the following figure 5,

Connection 

Now choose database objects in Entity Data Model Wizard and select Table which we would like to display then click on Finish. Here's figure 6 showing the same,

Wizard

Design the form as in the following figure 7,

Design 

Write the following code,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using System.Windows.Forms;  
  10.   
  11. namespace WindowsEntityFramework   
  12. {  
  13.     publicpartialclassForm1: Form  
  14.     {  
  15.         CMS1Entities objet = newCMS1Entities();  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         privatevoid Form1_Load(object sender, EventArgs e)  
  22.         {  
  23.             dataGridView1.DataSource = objet.EMP.ToList();  
  24.         }  
  25.   
  26.         privatevoid btnSave_Click(object sender, EventArgs e)  
  27.         {  
  28.             objet.SaveChanges();  
  29.             MessageBox.Show("Data has saved/display successfully");  
  30.         }  
  31.     }  
  32. }  
Now run the application and check it.

Recap: Entity framework is an OR mapping tool. The methods of Entity framework is SaveChanges ().

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now