Introduction
In this article, we will learn how to perform CRUD operations in a Windows Forms application using Entity Framework.
To learn more about Entity Framework, please visit here.
Step 1
First, we have to create a 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 the SQL Server 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. I have used labels, text boxes, combo boxes, Data GridView, and buttons here.
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 to your project. To add, right-click your solution and select Add - > New Item -> Select "Data" in the left pane and select "Ado.Net Entity Model."
Note
Here, I have used the DB-First approach in Entity Framework. If you are unaware 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, we create our custom model class for binding and displaying the values.
Note
Don't forget to declare your class as "public." Only then can you 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 the form is loading, and 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
}
// Display Method is a common method to bind the Student details in datagridview after save,update and delete operation perform.
public void Display()
{
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 the "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, passing this to the the "SaveStudentDetails" method, and saving the entity.
private void btnSave_Click(object sender, EventArgs e) // Save button click event
{
StudentDetail stu = new StudentDetail();
stu.Name = txtName.Text;
stu.Age = Convert.ToInt32(txtAge.Text);
stu.City = txtCity.Text;
stu.Gender = cmbGender.SelectedItem.ToString();
// calling SaveStudentDetails method to save the record in table.Here passing a student details object as parameter
bool result = SaveStudentDetails(stu);
ShowStatus(result, "Save");
}
public bool SaveStudentDetails(StudentDetail Stu) // calling SaveStudentMethod for insert a new record
{
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. I have written the 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) //Calling Datagridview cell click to Update and Delete
{
if (dataGridView1.Rows.Count > 0)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows) // foreach datagridview selected rows values
{
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) // Update button click event
{
StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString());
// Binding values to StudentInformationModel
bool result = UpdateStudentDetails(stu); // calling UpdateStudentDetails Method
ShowStatus(result, "Update");
}
public bool UpdateStudentDetails(StudentDetail Stu) // UpdateStudentDetails method for update a existing Record
{
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) //Delete Button Event
{
StudentDetail stu = SetValues(Convert.ToInt32(lblID.Text), txtName.Text, Convert.ToInt32(txtAge.Text), txtCity.Text, cmbGender.SelectedItem.ToString());
// Binding values to StudentInformationModel
bool result = DeleteStudentDetails(stu); //Calling DeleteStudentDetails Method
ShowStatus(result, "Delete");
}
public bool DeleteStudentDetails(StudentDetail Stu) // DeleteStudentDetails method to delete record from table
{
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) //Setvalues method for binding field values to StudentInformation Model class
{
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) // validate the Operation Status and Show the Messages To User
{
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() // Clear the fields after Insert or Update or Delete operation
{
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.