CRUD Operation Using Entity Framework In Windows Form Application

In this article, we are going to learn how to perform CRUD operations in a Windows Forms application using Entity Framework.
 
To know more about Entity Framework, please visit here.
 
Step 1
 
First, we have to create database and table in SQL Server. Please find the below scripts for creating the database and table respectively.
 
DB Script 
  1. create database StudentInformation;  
  2. Go;  
 Table Script
  1. CREATE TABLE [dbo].[StudentDetails](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [Age] [intNULL,  
  5.     [City] [varchar](50) NULL,  
  6.     [Gender] [varchar](50) NULL,  
  7.  CONSTRAINT [PK_StudentDetails] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [Id] ASC  
  10. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  11. ON [PRIMARY]  
 Here, I have used SQL Server 2008 SP1 version.
 
Step 2
 
Create a Windows application project in Visual Studio. Please find the below images for your reference.
 
 
 
 
Step 3
 
Design a form as per your requirement. Here, I have used labels, text-boxes, combo-boxes, Data GridView, and buttons.
 
Please find the below images for your reference.
 
 
 
Note

Here, the ID label is a hidden field.
 
Step 4
 
Add the ADO.NET Entity model in your project. To add, right click your solution and select Add - > New Item -> Select "Data" in left pane and select "Ado.Net Entity Model".
 
Note

Here, I have used DB-First approach in Entity Framework. If you are not aware of DB-First approaches, I have already provided the link at the top. Please visit the link for more clarification. 
 
Please find the below image for your reference.
 
 
 
 
 
 
Step 5
 
Now, you can see the added Entity Model in your Solution Explorer.
 
 
Step 6
 
Next, let us create our custom model class for binding and displaying the values.
 
Note

Don't forget to declare your class as "public". Then only you can access this class outside of any other class.
 
Please find the below code for your reference.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace WindowsFormsApplication1.Models  
  7. {  
  8.    public class StudentInformation  
  9.     {  
  10.         public int Id { getset; }  
  11.         public string Name { getset; }  
  12.         public int? Age { getset; }  
  13.         public string City { getset; }  
  14.         public string Gender { getset; }  
  15.     }  
  16. }  
Step 7
 
Bind the Student Details in Data GridView when form is loading and as well as we have to bind the values for Gender combo-box values. 
 
Please find the below code for your reference.
  1. private void Form1_Load(object sender, EventArgs e)  // Form load Method
  2.        {  
  3.            cmbGender.Items.Add("Male");   // Adding values for Gender Combobox
  4.            cmbGender.Items.Add("Female");  
  5.            Display();   // calling Display Method for Bind the Student Details in Datagridview
  6.        }  
  7.   
  8.        public void Display()   // Display Method is a common method to bind the Student details in datagridview after save,update and delete operation perform.
  9.        {  
  10.            using (StudentInformationEntities _entity=new StudentInformationEntities())  
  11.            {  
  12.                List<StudentInformation> _studentList = new List<StudentInformation>();  
  13.                _studentList = _entity.StudentDetails.Select(x => new StudentInformation  
  14.                {  
  15.                    Id=x.Id,  
  16.                    Name=x.Name,  
  17.                    Age=x.Age,  
  18.                    City=x.City,  
  19.                    Gender=x.Gender  
  20.                }).ToList();  
  21.                dataGridView1.DataSource = _studentList;  
  22.            }  
  23.        }  
Step 8
 
 Now, let's write the code for "Save" button.
 
Click the "Save" button and write the below code. "SaveStudentDetails" is a method to update the entity. 
 
Here, we are binding our input values (Name, Age, City, Gender) into StudentDetails class and passing this to "SaveStudentDetails" method and saving the entity. 
  1. private void btnSave_Click(object sender, EventArgs e)   // Save button click event  
  2.         {  
  3.             StudentDetail stu = new StudentDetail();  
  4.             stu.Name = txtName.Text;     
  5.             stu.Age = Convert.ToInt32(txtAge.Text);  
  6.             stu.City = txtCity.Text;  
  7.             stu.Gender = cmbGender.SelectedItem.ToString();  
  8.             bool result = SaveStudentDetails(stu); // calling SaveStudentDetails method to save the record in table.Here passing a student details object as parameter  
  9.             ShowStatus(result, "Save");  
  10.         }  
  11.         public bool SaveStudentDetails(StudentDetail Stu) // calling SaveStudentMethod for insert a new record  
  12.         {  
  13.             bool result = false;  
  14.             using (StudentInformationEntities _entity = new StudentInformationEntities())  
  15.             {  
  16.                 _entity.StudentDetails.AddObject(Stu);    
  17.                 _entity.SaveChanges();   
  18.                 result = true;  
  19.             }  
  20.             return result;  
  21.         }  
Now, we can try to add some records. Click F5 to run the application and fill in the input fields; then, click Save. Please find the below screenshots.
 
Note

Here, we are not validating the input fields. If you want, you can validate these.
 
 
 
 

Update & Delete
 
Next, write the code for update and delete operations. To update the record, we have to select the record from data GridView. Here, I have written datagridview cell click event to get the values from datagridview to fields. Please find the below code for your reference.
 
Note

We have to select the record from datagridview for update and delete. The same event will help us to get the records. 
  1. private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) //Calling Datagridview cell click to Update and Delete  
  2.        {  
  3.            if (dataGridView1.Rows.Count > 0)  
  4.            {  
  5.                foreach (DataGridViewRow row in dataGridView1.SelectedRows) // foreach datagridview selected rows values  
  6.                {  
  7.                    lblID.Text = row.Cells[0].Value.ToString();   
  8.                    txtName.Text = row.Cells[1].Value.ToString();  
  9.                    txtAge.Text = row.Cells[2].Value.ToString();  
  10.                    txtCity.Text = row.Cells[3].Value.ToString();  
  11.                    cmbGender.SelectedItem = row.Cells[4].Value.ToString();  
  12.                }  
  13.            }  
  14.        }  
Please find the below code for "Update".
  1. private void btnUpdate_Click(object sender, EventArgs e) // Update button click event  
  2.        {  
  3.            StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString()); // Binding values to StudentInformationModel  
  4.            bool result = UpdateStudentDetails(stu); // calling UpdateStudentDetails Method  
  5.            ShowStatus(result, "Update");  
  6.        }  
  7.        public bool UpdateStudentDetails(StudentDetail Stu) // UpdateStudentDetails method for update a existing Record  
  8.        {  
  9.            bool result = false;  
  10.            using (StudentInformationEntities _entity = new StudentInformationEntities())  
  11.            {  
  12.                StudentDetail _student = _entity.StudentDetails.Where(x => x.Id == Stu.Id).Select(x => x).FirstOrDefault();  
  13.                _student.Name = Stu.Name;  
  14.                _student.Age = Stu.Age;  
  15.                _student.City = Stu.City;  
  16.                _student.Gender = Stu.Gender;  
  17.                _entity.SaveChanges();  
  18.                result = true;  
  19.            }  
  20.            return result;  
  21.        }  
Please find the below code for "Delete".
  1. private void btnDelete_Click(object sender, EventArgs e) //Delete Button Event  
  2.        {  
  3.            StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString()); // Binding values to StudentInformationModel  
  4.            bool result = DeleteStudentDetails(stu); //Calling DeleteStudentDetails Method  
  5.            ShowStatus(result, "Delete");  
  6.        }  
  7.        public bool DeleteStudentDetails(StudentDetail Stu) // DeleteStudentDetails method to delete record from table  
  8.        {  
  9.            bool result = false;  
  10.            using (StudentInformationEntities _entity = new StudentInformationEntities())  
  11.            {  
  12.                StudentDetail _student = _entity.StudentDetails.Where(x => x.Id == Stu.Id).Select(x => x).FirstOrDefault();  
  13.                _entity.StudentDetails.DeleteObject(_student);    
  14.                _entity.SaveChanges();  
  15.                result = true;  
  16.            }  
  17.            return result;  
  18.        }  
 Let's perform Update and Delete operations.

 

 
 
 
 
Please find some external methods we have used here.
  1. public StudentDetail SetValues(int Id, string Name, int age, string City, string Gender) //Setvalues method for binding field values to StudentInformation Model class  
  2.       {  
  3.           StudentDetail stu = new StudentDetail();  
  4.           stu.Id = Id;  
  5.           stu.Name = Name;  
  6.           stu.Age = age;  
  7.           stu.City = City;  
  8.           stu.Gender = Gender;  
  9.           return stu;  
  10.       }  
  11.   
  12.       public void ShowStatus(bool result, string Action) // validate the Operation Status and Show the Messages To User  
  13.       {   
  14.           if (result)  
  15.           {  
  16.               if (Action.ToUpper() == "SAVE")  
  17.               {  
  18.                   MessageBox.Show("Saved Successfully!..""Save", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  19.               }  
  20.               else if (Action.ToUpper() == "UPDATE")  
  21.               {  
  22.                   MessageBox.Show("Updated Successfully!..""Update", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  23.               }  
  24.               else  
  25.               {  
  26.                   MessageBox.Show("Deleted Successfully!..""Delete", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  27.               }  
  28.           }  
  29.           else  
  30.           {  
  31.               MessageBox.Show("Something went wrong!. Please try again!..""Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);  
  32.           }  
  33.           ClearFields();  
  34.           Display();  
  35.       }  
  36.   
  37.       public void ClearFields() // Clear the fields after Insert or Update or Delete operation  
  38.       {  
  39.           txtName.Text = "";  
  40.           txtAge.Text = "";  
  41.           txtCity.Text = "";  
  42.           cmbGender.SelectedIndex = -1;  
  43.       }  
Thanks for reading this article. Please add comments if you have any queries regarding the process.

Up Next
    Ebook Download
    View all
    Learn
    View all