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
- create database StudentInformation;
- Go;
Table Script
- CREATE TABLE [dbo].[StudentDetails](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NULL,
- [Age] [int] NULL,
- [City] [varchar](50) NULL,
- [Gender] [varchar](50) NULL,
- CONSTRAINT [PK_StudentDetails] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace WindowsFormsApplication1.Models
- {
- public class StudentInformation
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public int? Age { get; set; }
- public string City { get; set; }
- public string Gender { get; set; }
- }
- }
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.
- private void Form1_Load(object sender, EventArgs e) // Form load Method
- {
- cmbGender.Items.Add("Male"); // Adding values for Gender Combobox
- cmbGender.Items.Add("Female");
- Display(); // calling Display Method for Bind the Student Details in Datagridview
- }
-
- public void Display() // Display Method is a common method to bind the Student details in datagridview after save,update and delete operation perform.
- {
- using (StudentInformationEntities _entity=new StudentInformationEntities())
- {
- List<StudentInformation> _studentList = new List<StudentInformation>();
- _studentList = _entity.StudentDetails.Select(x => new StudentInformation
- {
- Id=x.Id,
- Name=x.Name,
- Age=x.Age,
- City=x.City,
- Gender=x.Gender
- }).ToList();
- dataGridView1.DataSource = _studentList;
- }
- }
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.
- private void btnSave_Click(object sender, EventArgs e)
- {
- StudentDetail stu = new StudentDetail();
- stu.Name = txtName.Text;
- stu.Age = Convert.ToInt32(txtAge.Text);
- stu.City = txtCity.Text;
- stu.Gender = cmbGender.SelectedItem.ToString();
- bool result = SaveStudentDetails(stu);
- ShowStatus(result, "Save");
- }
- public bool SaveStudentDetails(StudentDetail Stu)
- {
- bool result = false;
- using (StudentInformationEntities _entity = new StudentInformationEntities())
- {
- _entity.StudentDetails.AddObject(Stu);
- _entity.SaveChanges();
- result = true;
- }
- return result;
- }
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.
- private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
- {
- if (dataGridView1.Rows.Count > 0)
- {
- foreach (DataGridViewRow row in dataGridView1.SelectedRows)
- {
- lblID.Text = row.Cells[0].Value.ToString();
- txtName.Text = row.Cells[1].Value.ToString();
- txtAge.Text = row.Cells[2].Value.ToString();
- txtCity.Text = row.Cells[3].Value.ToString();
- cmbGender.SelectedItem = row.Cells[4].Value.ToString();
- }
- }
- }
Please find the below code for "Update".
- private void btnUpdate_Click(object sender, EventArgs e)
- {
- StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString());
- bool result = UpdateStudentDetails(stu);
- ShowStatus(result, "Update");
- }
- public bool UpdateStudentDetails(StudentDetail Stu)
- {
- bool result = false;
- using (StudentInformationEntities _entity = new StudentInformationEntities())
- {
- StudentDetail _student = _entity.StudentDetails.Where(x => x.Id == Stu.Id).Select(x => x).FirstOrDefault();
- _student.Name = Stu.Name;
- _student.Age = Stu.Age;
- _student.City = Stu.City;
- _student.Gender = Stu.Gender;
- _entity.SaveChanges();
- result = true;
- }
- return result;
- }
Please find the below code for "Delete".
- private void btnDelete_Click(object sender, EventArgs e)
- {
- StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString());
- bool result = DeleteStudentDetails(stu);
- ShowStatus(result, "Delete");
- }
- public bool DeleteStudentDetails(StudentDetail Stu)
- {
- bool result = false;
- using (StudentInformationEntities _entity = new StudentInformationEntities())
- {
- StudentDetail _student = _entity.StudentDetails.Where(x => x.Id == Stu.Id).Select(x => x).FirstOrDefault();
- _entity.StudentDetails.DeleteObject(_student);
- _entity.SaveChanges();
- result = true;
- }
- return result;
- }
Let's perform Update and Delete operations.
Please find some external methods we have used here.
- public StudentDetail SetValues(int Id, string Name, int age, string City, string Gender)
- {
- StudentDetail stu = new StudentDetail();
- stu.Id = Id;
- stu.Name = Name;
- stu.Age = age;
- stu.City = City;
- stu.Gender = Gender;
- return stu;
- }
-
- public void ShowStatus(bool result, string Action)
- {
- if (result)
- {
- if (Action.ToUpper() == "SAVE")
- {
- MessageBox.Show("Saved Successfully!..", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else if (Action.ToUpper() == "UPDATE")
- {
- MessageBox.Show("Updated Successfully!..", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
- {
- MessageBox.Show("Deleted Successfully!..", "Delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- }
- else
- {
- MessageBox.Show("Something went wrong!. Please try again!..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- }
- ClearFields();
- Display();
- }
-
- public void ClearFields()
- {
- txtName.Text = "";
- txtAge.Text = "";
- txtCity.Text = "";
- cmbGender.SelectedIndex = -1;
- }
Thanks for reading this article. Please add comments if you have any queries regarding the process.