CRUD Operation in C# Windows Application - Codebun (2023)

How to create, read, update and delete operations in C# using MYSQL. In this C# Windows applicationLet's create a simple Windows application to perform the CRUD operations.

What are CRUD operations?

CRUD Meaning:CRUD is a combination of four functions that arecreate, read, updateandClearrequired to maintain any storage application basically shows the four main functions that can be performed on any database connected to our application.

CRUD databases and their associated applications to manage them

The CRUD applications are the ones that contain the basic CRUD functions present in various RDBMS systems like Microsoft SQL Server, MySQL, Oracle database and others. The four functions used by users to perform different types of operations on selected data in the database. This could be done using just code or via a GUI (graphical user interface).

CRUD operations in C# Windows application

Let's create a C# window application and database, then we will see how to connect them together and perform CRUD operations on them.

Creating a C# window form and database with table

In the example below, we'll see how to create a Windows application and add controls to the form, as well as create a database and tables.

Step 1:

OpenStudio visuals> then clickfile menu> clickNeu>then click onProject.

CRUD Operation in C# Windows Application - Codebun (1)

Step 2:

New Project dialog box.is displayed, selectVisual C# templates> then select .Net-Framework> Select"WindowForms-App (.Net Framework)“.
CRUD Operation in C# Windows Application - Codebun (2)

Step 3:

Once the application is created, we'll start adding controls from the Toolbox section and then provide the correct names for the controls.

CRUD Operation in C# Windows Application - Codebun (3)

Step 4:

Now let's create a database and a table in SQL Server. open that"Microsoft SQL Server Management Studio"> then right click on"Database"Folder > then click on"New Database".

CRUD Operation in C# Windows Application - Codebun (4)

Among"New Database"dialog box appears, enter a new database name as"dbEmployee Details"and clickOK.

Step 5:

Then run a new make-table query given below in the SQL window to create a new oneEmp_details table.

CREATE TABLE [dbo].[Emp_details]([EmpId] [int] NOT NULL,[EmpName] [nvarchar](50) NULL,[EmpAge] [int] NULL,[EmpContact] [int] NULL,[EmpGender] [ nchar](10) NULL )

Now we can also check table columns by right clicking and clicking on the newly created table"Design". The table looks like below in SQL Studio, now we have successfully created a database.

CRUD Operation in C# Windows Application - Codebun (5)

Connect database to C# window application

We will now see how to create a database connection between Windows application and database, how to get, insert, update and delete data from database (CRUD operation).

Step 1:

We can easily add database connection in windows application, just follow the simple steps,
Go toTools menuthen > click"Connect to database".

CRUD Operation in C# Windows Application - Codebun (6)

Step 2:

By default, theMicrosoft SQL-Server (SQL-Client)is selected as the data source.
Then provide"Servername"topremises HostandSelect our database as in the drop-down list„dbEmployeeDetails“.

CRUD Operation in C# Windows Application - Codebun (7)

Step 3:

We need to check the database connection by clicking"test connection"button, once the connection is confirmed you will see the"Test connection successful"message box.

CRUD Operation in C# Windows Application - Codebun (8)

Step 4:

When the database connection is created, the connection details are displayed.

CRUD Operation in C# Windows Application - Codebun (9)

Step 5:

How can we know the connection string?
Select right clickdatabase connection>Characteristics> Copy"connection string"for reference,

CRUD Operation in C# Windows Application - Codebun (10)

Step 6:

As a first step, we need to add a connection string„App.config“file to connect the database,

CRUD Operation in C# Windows Application - Codebun (11)

Step 7: Enter the employee details

First we need to create an Employee class and its properties,

public class { public string EmpId { get; set; } public string EmpName { get; set; } public string age { get; set; } public string ContactNo { get; set; }}

Now add the connection string read outApp.configuseconfiguration manager,

privatestaticstringmyConn=ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

The method accepts employee details and then opens the SQL connection and runs the command to insert the employee details into the databaseINSERTIONQuery if successful then returntrueor butNOT CORRECT.

private const string InsertQuery = "Insert In Emp_details(EmpId, EmpName, EmpAge, EmpContact, EmpGender) Values ​​(@EmpId, @EmpName, @EmpAge, @EmpContact, @EmpGender)";public bool InsertEmployee(Employee employee){int rows; using (SqlConnection con = new SqlConnection(myConn)){con.Open();using (SqlCommand com = new SqlCommand(InsertQuery, con)){com.Parameters.AddWithValue("@EmpId", employee.EmpId);com. Parameters.AddWithValue("@EmpName", Employee.EmpName);com.Parameters.AddWithValue("@EmpAge", Employee.Age);com.Parameters.AddWithValue("@EmpContact", Employee.ContactNo);com.Parameters. AddWithValue("@EmpGender", employee.Gender);rows = com.ExecuteNonQuery();} }return (rows > 0) ? wahr falsch;}

Step 8: Update employees

The UpdateEmployee method accepts updated employee details and opens a SQL connection and updates the employee details in the database with itTO UPDATEQuery returns on successtrueor butNOT CORRECT.

private const string UpdateQuery = "Emp_details aktualisieren set EmpName=@EmpName, EmpAge=@EmpAge, EmpContact=@EmpContact, EmpGender=@EmpGender where EmpId=@EmpId";public bool UpdateEmployee(Employee employee){int rows;using (SqlConnection con = new SqlConnection(myConn)){con.Open();using (SqlCommand com = new SqlCommand(UpdateQuery, con)){com.Parameters.AddWithValue("@EmpName", employee.EmpName);com.Parameters.AddWithValue( "@EmpAge", Mitarbeiter.Alter); com.Parameters.AddWithValue("@EmpContact", Employee.ContactNo);com.Parameters.AddWithValue("@EmpGender", Employee.Gender); com.Parameters.AddWithValue("@EmpId", employee.EmpId);rows = com.ExecuteNonQuery();} }return (rows > 0) ? wahr falsch;}

Step 9: Delete employees

The DeleteEmplee method passes the selected employee ID to delete the employee details in the databaseCLEARInquiry. if it succeeds, then it returnstrueotherwise it returns false.

private const string DeleteQuery = "Delete from Emp_details where EmpId=@EmpId";public bool DeleteEmployee(Employee employee){int rows;using (SqlConnection con = new SqlConnection(myConn)){con.Open();using (SqlCommand com = new SqlCommand(DeleteQuery, con)){com.Parameters.AddWithValue("@EmpId", employee.EmpId);rows = com.ExecuteNonQuery();} }return (rows > 0) ? wahr falsch;}

Step 10: Get employee details

The methodGet staffreturns all employees stored in the databaseSELECTquery as shown below,

privateconststringSelectQuery="Select*fromEmp_details";public DataTable GetEmployees(){var datatable = new DataTable();using (SqlConnection con = new SqlConnection(myConn)){con.Open();using(SqlCommand com = new SqlCommand(SelectQuery, con)){using(SqlDataAdapter adapter = new SqlDataAdapter(com)){adapter.Fill(datatable);} } } return datatable;}

The Employee class now looks like this,

Using System;Using System.Collections.Generic;Using System.Configuration;Using System.Data;Using System.Data.SqlClient;Using System.Linq;Using System.Text;Using System.Threading. Tasks;Namespace EmployeeDetails
{class Employee{private static string myConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;public string EmpId { get; set; } public string EmpName { get; set; } public string age { get; set; }public string ContactNumber { get; set; } public string gender { get; set; }private const string SelectQuery = "Select * from Emp_details";private const string InsertQuery = "Insert In Emp_details(EmpId, EmpName, EmpAge, EmpContact, EmpGender) Values ​​​​(@EmpId, @EmpName, @EmpAge, @EmpContact, @ EmpGender) ";private const string UpdateQuery = "Update Emp_details set EmpName=@EmpName, EmpAge=@EmpAge, EmpContact=@EmpContact, EmpGender=@EmpGender where EmpId=@EmpId";private const string DeleteQuery = "Delete from Emp_details where EmpId => EmpId";public DataTable GetEmployees(){var datatable = new DataTable();using (SqlConnection con = new SqlConnection(myConn)){con.Open();using(SqlCommand com = new SqlCommand(SelectQuery, con)) {using (SqlDataAdapter adapter = new SqlDataAdapter(com)){adapter.Fill(datatable);} } }return datatable;}public bool InsertEmployee(Employee employee){int rows;using (SqlConnection con = new SqlConnection(myConn))){ con. Open();using (SqlCommand com = new SqlCommand(InsertQuery, con)){com.Parameters.AddWithValue("@EmpId", employee.EmpId);com.Param eters.AddWithValue("@EmpName", Employee.EmpName) ;com.Parameters.AddWithValue("@EmpAge", Employee.Age);com.Parameters.AddWithValue("@EmpContact", Employee.ContactNo);com.Parameters. AddWithValue("@EmpGender", employee.Gender);rows = com.ExecuteNonQuery();} }return (rows > 0) ? true: false;}public bool UpdateEmployee(Employee employee){int rows;using (SqlConnection con = new SqlConnection(myConn)){con.Open();using (SqlCommand com = new SqlCommand(UpdateQuery, con)){ com. Parameters.AddWithValue("@EmpName", Employee.EmpName);com.Parameters.AddWithValue("@EmpAge", Employee.Age);com.Parameters.AddWithValue("@EmpContact", Employee.ContactNo);com.Parameters. AddWithValue("@EmpGender", employee.Gender);com.Parameters.AddWithValue("@EmpId", employee.EmpId);rows = com.ExecuteNonQuery();} }return (rows > 0) ? true : false;}public bool DeleteEmployee(Employee employee){int rows;using (SqlConnection con = new SqlConnection(myConn)){con.Open();using (SqlCommand com = new SqlCommand(DeleteQuery, con)){com. Parameters.AddWithValue("@EmpId", employee.EmpId);rows = com.ExecuteNonQuery();} }return (rows > 0) ? true false;} } }

We have now completed all the operations and we can insert, update, delete and get the employee details using the methods.

Step 11: How Can We Perform the CRUD Operations Using Windows Forms?

Double-click the"Add"button, It automatically opens theForm1.csand create below click event method and we need to write some logic here. All buttons have their click events when we click that button and fire the associated event at that time.

private void btnAdd_Click(object sender, EventArgs e){}
using System;using System.Windows.Forms;namespace EmployeeDetails{public subclass Form1 : Form{Employee employee = new Employee();public Form1(){InitializeComponent();dgvEmployeeDetails.DataSource = employee.GetEmployees();} // Employee details add when Add button is clicked private void btnAdd_Click(object sender, EventArgs e){ employee.EmpId = txtEmpId.Text;employee.EmpName = txtEmpName.Text;employee.Age = txtAge.Text;employee.ContactNo = txtContactNo .Text; employee.Gender = cboGender.SelectedItem.ToString();// Call the Insert Employee method to insert the employee details into the databasevar success = employee.InsertEmployee(employee); // Refresh the grid to show the updated employee details dgvEmployeeDetails.DataSource = employee.GetEmployees();if (success){// Clear controls once employee is inserted successfullyClearControls();MessageBox.Show("Employee has been been added successfully" );}elseMessageBox.Show("An error occurred. Please try again...");}//Updates the details of the selected employee when you click the refresh button. employee.Age = txtAge.Text;employee.ContactNo = txtContactNo.Text;employee.Gender = cboGender.SelectedItem.ToString();// Call the Update Employee method to update the selected employee details to the databasevar success = employee.UpdateEmployee(employee) ;// Refresh the grid to see the updated employee details. );}elseMessageBox.Show("An error occurred. Please try again...");}// Delete the selected employee when the delete button is clickedprivate void btnDelete_Click(object sender, EventArgs e){employee. EmpId = txtEmpId.Text;// Call DeleteEmployee method to delete the selected employee from the databasevar success = employee.DeleteEmployee(employee);// Refresh the grid to show the updated employee details ("Employee was added successfully" );}elseMessageBox.Show("An error occurred. Please try again...");}// Clear all controls when clicks clear buttonprivate void btnClear_Click(object sender, EventArgs e){ClearControls( );}private void ClearControls(){txtEmpId.Text = "";txtEmpName.Text = "";txtAge.Text = "";txtContactNo.Text = "";cboGender.Text = "";}// This data grid event is fired when You select the grid rows and the controls with selected collaborators Fill eiterdetailsprivate void dgvEmployeeDeta ils_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e){var index = e.RowIndex;txtEmpId.Text = dgvEmployeeDetails.Rows[index].Cells[0].Value.ToString();txtEmpName.Text = dgvEmployeeDetails.Rows[ index].Cells[1].Value.ToString();txtAge.Text = dgvEmployeeDetails.Rows[index].Cells[2].Value.ToString();txtContactNo.Text = dgvEmployeeDetails.Rows[index].Cells[3 ].Value. ToString();cboGender.Text = dgvEmployeeDetails.Rows[index].Cells[4].Value.ToString();} } }

Output:

CRUD Operation in C# Windows Application - Codebun (12)

Add employee details and click the Add button.

CRUD Operation in C# Windows Application - Codebun (13)

The employee data was successfully inserted.

CRUD Operation in C# Windows Application - Codebun (14)

Selecting the grid row (Employees) populates selected employee details in the update or delete controls.

CRUD Operation in C# Windows Application - Codebun (15)

So this way we can just create a C# windows application and database connected together and then we can do basic CRUD operations on it. I hope you all have now learned the process.

Also check out these articles on C# tutorials:

  • How to generate PDF files in a C# Windows application
  • Login and Registration Form Validation in C#
  • How to calculate age from DOB in C#
  • Session and Cookie Management in ASP.NET
  • Hide and show password text using checkbox in C# Windows application
  • How to get selected value of radio button in Asp.net with C#
  • How to send an email in a C# Windows application
  • How to get checkbox value with in asp.net with C#
  • Upload and download images in C# Windows application
  • Check the email id in the C# desktop application

FAQs

How to send mail using C# net Windows application? ›

Sending emails from C# using an SMTP server requires only a few lines of code: var smtpClient = new SmtpClient("smtp.gmail.com") { Port = 587, Credentials = new NetworkCredential("username", "password"), EnableSsl = true, }; smtpClient. Send("email", "recipient", "subject", "body");

What are the 4 CRUD components? ›

CRUD is an acronym that comes from the world of computer programming and refers to the four functions that are considered necessary to implement a persistent storage application: create, read, update and delete.

How to create complete login and registration system in C#? ›

Right-click on the solution name then Hover the mouse on Add and click on Add New Item, or you can user short cut key “Ctrl+Shift+A”. Now you see a dialog where we add our forms. Select Windows Form, give it a proper name and click on Add. Add a Login, Registration, and Home page in the same way.

How to send mail without SMTP server in C#? ›

The simplest way to send a message is to use QuickSend method of Smtp class (this method is static, it does not require you to create an instance of Smtp class). QuickSend method allows you to send e-mails out even if you do not have an SMTP relay server.

How to send mail using SMTP server in C# without password? ›

An SMTP server that needs no authentication should be protected by a firewall, to prevent outsiders from using it as a SPAM server. To send email without logging in, simply set the mailman's SmtpAuthMethod property = "NONE".

Is CRUD part of REST API? ›

CRUD functions can exist in a REST API, but REST APIs are not limited to CRUD functions. CRUD can operate within a REST architecture, but REST APIs can exist independent of CRUD. For example, a REST API can allow clients to reboot a server even if it doesn't correspond to any CRUD functions.

What is a CRUD REST API? ›

CRUD stands for Create, Read, Update, and Delete, which make up these four fundamental operations. Because REST API calls invoke CRUD operations, understanding their relationship with one another is important for API developers and data engineers.

What is CRUD in coding? ›

CRUD (Create, Read, Update, Delete) is an acronym for ways one can operate on stored data. It is a mnemonic for the four basic functions of persistent storage.

What is SSO authentication in C#? ›

What is single sign-on (SSO)? Users must authenticate themselves to access pages protected by a web application, and if a user accesses multiple web applications, they must be authenticated. You must log in to each application separately.

What is CRUD in SQL? ›

CRUD is an acronym for CREATE, READ(SELECT), UPDATE, and DELETE statements in SQL Server. CRUD in database terms can be mentioned as Data Manipulation Language (DML) Statements as well. Data Manipulation Language is used to manage or manipulate the data present inside database Tables.

What is CRUD in scrum? ›

Developers are familiar with the acronym CRUD, which indicates operations Create, Read, Update, and Delete. And exactly these operations are the most common example. Others may be e.g., Archiving, Export, Import, Registration, and Login.

Which API is used to carry out CRUD operations? ›

CRUD stands for "Create, Read, Update, and Delete," which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs.

How to send email in C# Windows application with attachment? ›

Clicking on the 'Attach' button, a dialog box appears which asks the user to choose a file. Choosing a file, the textbox is populated with the path of the file. We click on the 'Send' button to send the mail. Finally, a message box appears stating that the mail is sent.

How to send email from Office 365 in C#? ›

Sending E-mail Using Office 365 and C#

Sending e-mail using Office 365 API is easy; developers just have to use the build feature in the SMTP client and the Mailmessage objects of . NET. You need to specify the host name, port, EnableSSL, and the credentials properties of the SmtpClient object.

Does Windows have SMTP server? ›

Installing an SMTP service is an easy task on Windows server as this is an in-built feature of the server.

How to read mail from SMTP server in C#? ›

You can use it like this. MailMessage message = new MailMessage(); message. From = new MailAddress("your.email.address@example.com", "Your name"); MailAddress recipientsMailAddress = new MailAddress("the.recipients.email@example.com"); message.

How to receive email in C#? ›

You can use the following code to fetch the topics of incoming mail: var client = new POPClient(); client. Connect("pop.gmail.com", 995, true);

Can you send email without port 25? ›

Port 25 is still known as the standard SMTP port and it's used mostly for SMTP relay. However, if you're setting up your WordPress site or email client with SMTP, you usually do not want to use port 25 because most residential ISPs and cloud hosting providers block port 25.

Can you brute force SMTP? ›

What Are Brute Force Mail Attacks? They're launched when someone uses automated password-guessing software to try and force a login to a mail account. If the attacker can login to the server with valid IMAP/SMTP credentials, they'll then use it to read incoming emails or send email spam via the user's email account.

What are the 4 most common REST API operations? ›

For REST APIs built on HTTP, the uniform interface includes using standard HTTP verbs to perform operations on resources. The most common operations are GET, POST, PUT, PATCH, and DELETE.

Which database type does CRUD? ›

CRUD is extensively used in database applications. This includes Relational Database Management Systems (RDBMS) like Oracle, MySQL, and PostgreSQL. It also includes NoSQL databases like MongoDB, Apache Cassandra, and AWS DynamoDB.

What is CRUD in Visual Studio? ›

Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework.

What are the CRUD operations explain with example? ›

The Definition of CRUD

Within computer programming, the acronym CRUD stands for create, read, update and delete. These are the four basic functions of persistent storage.

What is difference between REST API and RESTful API? ›

Put simply, there are no differences between REST and RESTful as far as APIs are concerned. REST is the set of constraints. RESTful refers to an API adhering to those constraints. It can be used in web services, applications, and software.

How do you update data in CRUD operation? ›

Update: In CRUD operations, 'U' is an acronym for the update, which means making updates to the records present in the SQL tables. So, we will use the UPDATE command to make changes in the data present in tables.

How to save data without database using C# in Windows application? ›

you can use xml serialization or binary serialization.

What is the difference between login form and registration form? ›

A Registration form is used to register or create a new account for a new user for a website and a login form is used to enter the details of a registered user into their particular account or portal.

What is difference between SSO and OAuth? ›

To Start, OAuth is not the same thing as Single Sign On (SSO). While they have some similarities — they are very different. OAuth is an authorization protocol. SSO is a high-level term used to describe a scenario in which a user uses the same credentials to access multiple domains.

How many types of authentication are there in C #? ›

Authentication providers

The ASP.net architecture includes the concept of and authentication provider a piece of code whose job is to verify credentials and decide whether a particular request should be considered authenticated. Out of the box ASP.net gives you a choice of three different authentication providers.

Does SSO replace MFA? ›

No. If MFA is enabled for your SSO identity provider, you don't need to enable Salesforce's MFA for users who log in via SSO. But if you have admins or other privileged users who log in to your Salesforce products directly, you do need to set up Salesforce's MFA for these users.

What is the curd in C#? ›

Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework - GeeksforGeeks.

Which language is used for CRUD operations? ›

The acronym CRUD refers to the major operations which are implemented by databases. Each letter in the acronym can be mapped to a standard Structured Query Language (SQL) statement.

Is REST API for CRUD operations? ›

CRUD functions can exist in a REST API, but REST APIs are not limited to CRUD functions. CRUD can operate within a REST architecture, but REST APIs can exist independent of CRUD. For example, a REST API can allow clients to reboot a server even if it doesn't correspond to any CRUD functions.

Is CRUD a data structure? ›

After creating a Data Structure capable of writing to the database, Designers maintain its data internally by implementing Create, Read, Update, and Delete (CRUD) actions via Flow steps. Was this article helpful?

How do you explain CRUD? ›

CRUD is the acronym for CREATE, READ, UPDATE and DELETE. These terms describe the four essential operations for creating and managing persistent data elements, mainly in relational and NoSQL databases.

What is a CRUD use case diagram? ›

The CRUD pattern consists of one use case, called CRUD. Information or Manage Information[1,7], modeling all the different operations that can be performed on. a piece of information of a certain kind, such as creating, reading, updating, and deleting it.

What is CRUD operations in API? ›

CRUD stands for "Create, Read, Update, and Delete," which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs. In this tutorial, you will build a very simple web API to manage a list of products.

Why is CRUD useful? ›

CRUD has a number of advantages, including: It simplifies security control by meeting a variety of access criteria. It makes application design easier and more scalable by simplifying and facilitating it. When compared to ad-hoc SQL statements, it performs better.

What are CRUD operations in HTML? ›

CRUD (Create, Read, Update, Delete) is an acronym for ways one can operate on stored data. It is a mnemonic for the four basic functions of persistent storage.

What is swagger in C #? ›

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Its main goals are to: Minimize the amount of work needed to connect decoupled services.

What is CRUD operations in MVC? ›

In the previous tutorial, you created an MVC application that stores and displays data using the Entity Framework (EF) 6 and SQL Server LocalDB. In this tutorial, you review and customize the create, read, update, delete (CRUD) code that the MVC scaffolding automatically creates for you in controllers and views.

References

Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated: 13/10/2023

Views: 6382

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.