CRUD Operation In Windows Form App Using The Entity Framework

Introduction

 
In this article, we perform CRUD Operations in a windows form application. For this CRUD operation, we are using the Entity framework. We perform all operations, such as create, update, delete and select using the entity framework.
 

What is Entity Framework?

 
Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.”
 

Perform CRUD Operations Using Entity Framework

 
Step 1
 
First of all, create a Windows Forms App. To create a new app click on file menu > New > New project and select Windows Forms App then click on Next button.
 
 
Step 2
 
In the next screen, you need to enter the following details, then click on the Create button
  • ProjectName - Enter your project name in this field. This is also your solution name.
  • Location - Path of where you want to store this project.
  • Framework - Select .Net framework version which you want to use in this project.
 
Step 3
 
Now your project is ready and you can see a new form open in your visual studio called Form1. Change some properties if you want like Text, which is the title shown on your form, color, background color, Windows state, etc. Here, I only change windows state and Text properties.
 
 
Step 4
 
Now create your design as your requirement. You can see in the below image that I added some controls in my form.
 
 
Step 5
 
Now we create our table in database. You can see in the below image I create a table with five columns where EmployeeId is the primary key and also auto increment.
  1. CREATE TABLE [dbo].[Employee](  
  2.     [EmployeeId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [EmployeeName] [nvarchar](50) NULL,  
  4.     [EmployeeAge] [intNULL,  
  5.     [EmployeeAddress] [nvarchar](200) NULL,  
  6.     [EmployeeCity] [nvarchar](50) NULL,  
  7.     [EmployeeSalary] [intNULL,  
  8.      CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  9.     (  
  10.         [EmployeeId] ASC  
  11.     )  
  12. )  
 
Step 6
 
Now we add Entity Data Model in our project for that I create a new folder in solution called Model. Then right-click in this folder. You see a context menu click on Add, then New Item.
 
 
Step 7
 
Now click on Data from left sidebar for see item related to database and then select ADO.NET Entity Data Model, give appropriate name and click on the Add button.
 
 
Step 8
 
Now you see the wizard for Entity Data Model. In this wizard, there are four options EF Designer from database, Empty EF Designer Model, Empty Code first model, Code first from database. Here, we have a database table, so we create first option and click on next button.
 
 
Step 9
 
In next step you need to connect with your SQL server. Click on New Connection it will open a new popup window.
 
 
Step 10
 
In this popup window, you need to perform the following operations.
 
  • Select Your Data source. Here I use SQL Server so automatically here Microsoft SQL Server is selected, you can change it if you use another.
  • Server Name: here enter your server name. In my case I have SQL Server on same PC so I just enter (local) then it get all database from your server.
  • Select Database: Select database from drop-down list which you want to use for this project.
  • Then click on Test Connection button for check connection established successfully or not and then click on Ok button.
Step 11
 
Now you get a connection string. If you want to store the connection string in App.Config file, then check that checkbox and give your connection string name. Then click on the Next Button.
 
 
Step 12
 
In this step, it will ask you to choose entity framework version which include in this project. Select your version and click on the Next Button.
 
 
Step 13
 
In this step you see all tables, views and store procedures list which you have in your database select tables, views and store procedures as your requirement. Give name of Model Namespace and click on the finish button.
 
 
Now you can see in the below image that we have Entity Framework references in our project. Also, DbModels is created in our folder.
 
 
Step 14
 
Now we add columns in Data Grid View. If you want to show all columns from you table then you does not need to perform this step. Add columns you want to show and bind Data property with the Database column name.
 
 
Step 15
 
Now we are finished with the back end code. First of all, generate a Form_Load event by double-clicking on your form and add code, as shown below. Also, create an instance of your Entity Model class and a database table class.
 
Form Load Method
  1. //create object of contex and table model  
  2. TutorialEntities db = new TutorialEntities();  
  3. Employee Employee = new Employee();  
  4. int EmpId = 0;  
  5. /// <summary>  
  6. /// form load event  
  7. /// </summary>  
  8. /// <param name="sender"></param>  
  9. /// <param name="e"></param>  
  10. private void Form1_Load(object sender, EventArgs e)  
  11. {  
  12.     ClearData();  
  13.     SetDataInGridView();  
  14. }  
Clear Data function
  1. /// <summary>    
  2. /// reset all fields    
  3. /// </summary>    
  4. public void ClearData() {  
  5.     txtEmpAdd.Text = txtEmpAge.Text = txtEmpCity.Text = txtEmpName.Text = txtEmpSalary.Text = string.Empty;  
  6.     btnDelete.Enabled = false;  
  7.     btnSave.Text = "Save";  
  8.     EmpId = 0;  
  9. }  
In the above code, we set all textbox values to an empty string. Disable the delete button and set the save button text to save. And also set EmpId’s value 0 (zero) which we declare on top.
 
Set Data In Grid View Function
  1. /// <summary>  
  2. /// set data in grid view  
  3. /// </summary>  
  4. public void SetDataInGridView()  
  5. {  
  6.     dataGridView.AutoGenerateColumns = false;   
  7.     dataGridView.DataSource = db.Employees.ToList<Employee>();  
  8. }  
In this function, first, we set auto-generated the column false because we define our custom column and next get data from the Employee table and set it in the grid view data source.
 
Step 16
 
Now we add code for insert new record and update existing record. For this add button, click event on your form by double clicking on your save button. Add the following code in your button click event.
  1. /// <summary>  
  2. /// insert update data  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. private void btnSave_Click(object sender, EventArgs e)  
  7. {  
  8.     Employee.EmployeeName = txtEmpName.Text.Trim();  
  9.     Employee.EmployeeAge = Convert.ToInt32(txtEmpAge.Text.Trim());  
  10.     Employee.EmployeeAddress = txtEmpAdd.Text.Trim();  
  11.     Employee.EmployeeCity = txtEmpCity.Text.Trim();  
  12.     Employee.EmployeeSalary = Convert.ToInt32(txtEmpSalary.Text.Trim());  
  13.     if (EmpId > 0)  
  14.         db.Entry(Employee).State = EntityState.Modified;  
  15.     else  
  16.     {  
  17.         db.Employees.Add(Employee);  
  18.     }  
  19.     db.SaveChanges();  
  20.     ClearData();  
  21.     SetDataInGridView();  
  22.     MessageBox.Show("Record Save Successfully");  
  23.   
  24. }  
Code Explanation
  • In this above code, you can see we set data in the Employee Model object from textbox.
  • Next we check if EmpId’s value is greater than 0 which means we need to perform update operation. If value is greater than 0 then set state of Employee Entity modified else add this employee entity to employee collection.
  • Then save changes by calling the saveChanges() method of the DB object.
  • Then clear textbox data and refresh grid view data by calling set data in grid view method again.
  • Show message in last that data is saved.
Output
 
 
Step 17
 
Now we get data in the textbox when the user double-clicks on grid view. For this, add double click event in grid view from event tab.
 
Add the following code in your double click event.
  1. /// <summary>  
  2. /// set data in textbox on grid view click  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. private void dataGridView_DoubleClick(object sender, EventArgs e)  
  7. {  
  8.     if (dataGridView.CurrentCell.RowIndex != -1)  
  9.     {  
  10.         EmpId = Convert.ToInt32(dataGridView.CurrentRow.Cells["EmployeeId"].Value);  
  11.         Employee = db.Employees.Where(x => x.EmployeeId == EmpId).FirstOrDefault();  
  12.         txtEmpName.Text = Employee.EmployeeName;  
  13.         txtEmpAdd.Text = Employee.EmployeeAddress;  
  14.         txtEmpAge.Text = Employee.EmployeeAge.ToString();  
  15.         txtEmpSalary.Text = Employee.EmployeeSalary.ToString();  
  16.         txtEmpAge.Text = Employee.EmployeeAge.ToString();  
  17.         txtEmpCity.Text = Employee.EmployeeCity;  
  18.     }  
  19.     btnSave.Text = "Update";  
  20.     btnDelete.Enabled = true;  
  21. }  
Code Explanation
  • First, we check that the row index is not less than zero because we don’t want to do anything when the user clicks on the grid view header.
  • Then get the employee id by passing column name which we give in step 14.
  • Then get data from employee table by add where condition and assign this data to Employee object.
  • Then pass data from the Employee object to the textbox.
  • At last, enable the delete button and set the save button text to Update.
Output
 
 
Step 18
 
Now we perform a delete operation. Add a button click event and add following code:
  1. /// <summary>  
  2. /// delete record  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. private void btnDelete_Click(object sender, EventArgs e)  
  7. {  
  8.     if (MessageBox.Show("Are you sure you want to delete this record ?""Delete ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)  
  9.     {  
  10.         db.Employees.Remove(Employee);  
  11.         db.SaveChanges();  
  12.         ClearData();  
  13.         SetDataInGridView();  
  14.         MessageBox.Show("Record Deleted Successfully");  
  15.     }  
  16. }  
Code Explanation 
  • In the above code, first we show confirmation dialog to user if user want to delete record. If the user clicks yes then we perform the next step.
  • Then remove Employee entity from db.Employee. We already have data in the Employee object from step 17.
  • Call Save changes, clear data and set grid view data method and show message that record delete successfully.
Output
 
 
Step 19
 
Call the clear data function on a cancel button click event.
 
I hope you find this article useful. If so, then please share with your friends. If you have any doubts, comment below. You can also download the zip file of this project. Thank you.