How to Insert Update Delete Search Records in C#
By FoxLearn 7/20/2024 2:20:29 AM 13.81K
You'll need to follow a few steps to perform basic CRUD operations (Create, Read, Update, Delete) in a DataGridView in a Windows Forms Application using ADO.NET in C#
Open your Visual Studio, then create a new Windows Forms Application project.
Next, Drag and drop the TextBox, Button and DataGridView from the Visual Studio toolbox into your form designer.
You can modify your layout as shown below allowing you to perform the action of adding, deleting and searching for data with DataGridView in C# Winforms.
Next, Open your Microsoft SQL Server Management Studio, then run the sql script below to create a contact table.
CREATE TABLE [dbo].[Contacts]( [Id] [int] IDENTITY(1,1) NOT NULL, [FullName] [nvarchar](100) NULL, [Email] [varchar](100) NULL, [Address] [nvarchar](100) NULL, CONSTRAINT [PK_Contacts] 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] GO
Opening your app.config file, then add a connection string to the app.config file, don't forget to modify your connection string based on your user and password sql server.
<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="cn" connectionString="Data Source=.;Initial Catalog=dbtest;Persist Security Info=True;User ID=sa;Password=123@qaz" providerName="System.Data.SqlClient" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> </configuration>
Opening your form, then select code behind. You can create a connection string variable allows you to read the connection string in the app.config file.
string _connectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
and don't forget to add a reference to the System.Configuration.dll.
using System.Configuration;
Establish a connection to your database using ADO.NET. You'll need to use SqlConnection
, SqlCommand
, SqlDataAdapter
, etc., to interact with your database.
Creating an InitData method allows you to retrieve data from the contact table.
// c# get data from sql void InitData() { using (SqlConnection cn = new SqlConnection(_connectionString)) { DataTable dt = new DataTable("Customer"); SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from contacts", cn); dataAdapter.Fill(dt); dataGridView.DataSource = dt; } }
Adding a Form_Load event handler to your form allows you to retrieve contact data from the contact table.
private void frmContact_Load(object sender, EventArgs e) { InitData(); }
Creating a Clear method allows you to clear text data in your textbox control.
void Clear() { txtFullName.Text = string.Empty; txtEmail.Text = string.Empty; txtAddress.Text = string.Empty; }
Adding a click event handler to the Insert button allows you to insert data from textbox to contact table. Create an INSERT statement and execute it using SqlCommand
. After inserting the record, refresh the DataGridView to reflect the changes.
// c# insert data into sql private void btnInsert_Click(object sender, EventArgs e) { using (SqlConnection cn = new SqlConnection(_connectionString)) { if (cn.State == ConnectionState.Closed) cn.Open(); using (SqlCommand cmd = new SqlCommand("insert into contacts(fullname, email, address) values(@FullName, @Email, @Address)", cn)) { cmd.Parameters.AddWithValue("@FullName", txtFullName.Text); cmd.Parameters.AddWithValue("@Email", txtEmail.Text); cmd.Parameters.AddWithValue("@Address", txtAddress.Text); cmd.ExecuteNonQuery(); InitData(); Clear(); } } }
Adding a click event handler to the Update button allows you to update contact data from textbox control. Create an UPDATE statement and execute it using SqlCommand
. After updating the record, refresh the DataGridView.
// c# update data from sql private void btnUpdate_Click(object sender, EventArgs e) { using (SqlConnection cn = new SqlConnection(_connectionString)) { if (cn.State == ConnectionState.Closed) cn.Open(); using (SqlCommand cmd = new SqlCommand("update contacts set FullName = @FullName, Email = @Email, Address = @Address where Id = @Id", cn)) { DataGridViewRow row = dataGridView.Rows[dataGridView.CurrentRow.Index] as DataGridViewRow; if (row != null) { cmd.Parameters.AddWithValue("Id", row.Cells[0].Value); cmd.Parameters.AddWithValue("@FullName", txtFullName.Text); cmd.Parameters.AddWithValue("@Email", txtEmail.Text); cmd.Parameters.AddWithValue("@Address", txtAddress.Text); cmd.ExecuteNonQuery(); InitData(); } } } }
Adding a CellClick event handler to your DataGridView allows you to fill data from DataGridView to TextBox control.
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = dataGridView.Rows[dataGridView.CurrentRow.Index] as DataGridViewRow; if (row != null) { txtFullName.Text = row.Cells[1].Value.ToString(); txtEmail.Text = row.Cells[2].Value.ToString(); txtAddress.Text = row.Cells[3].Value.ToString(); } }
Adding a click event handler to the Delete button allows you to delete contact data in the contact table. Create a DELETE statement and execute it using SqlCommand
. After deleting the record, refresh the DataGridView.
// c# delete data from sql private void btnDelete_Click(object sender, EventArgs e) { DataGridViewRow row = dataGridView.Rows[dataGridView.CurrentRow.Index] as DataGridViewRow; if (row != null) { if (MessageBox.Show("Are you sure want to delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { using (SqlConnection cn = new SqlConnection(_connectionString)) { // Open connection if (cn.State == ConnectionState.Closed) cn.Open(); // Create DELETE statement using (SqlCommand cmd = new SqlCommand("delete from contacts where Id = @Id", cn)) { cmd.Parameters.AddWithValue("Id", row.Cells[0].Value); // Execute query and close connection cmd.ExecuteNonQuery(); // Refresh DataGridView InitData(); Clear(); } } } } }
Adding a KeyPress event handler to the search textbox control allows you to catch the enter key. Implement a search functionality where users can input search criteria, and you execute a SELECT statement with a WHERE clause to filter records. Then, bind the result to the DataGridView.
// c# search data in sql private void txtSearch_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { // Create SELECT statement with WHERE clause based on search criteria using (SqlConnection cn = new SqlConnection(_connectionString)) { DataTable dt = new DataTable("Customer"); SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from contacts where fullname like @Search", cn); dataAdapter.SelectCommand.Parameters.AddWithValue("@Search", $"%{txtSearch.Text}%"); dataAdapter.Fill(dt); dataGridView.DataSource = dt; } } }
Bind your DataGridView with a DataTable or a DataView. This can be done by setting the DataSource property of the DataGridView.
In this example, replace "Your_Connection_String" int the app.config with your actual connection string and adjust the SQL statements and table/column names accordingly. Also, you need to handle events for buttons like btnInsert_Click
, btnUpdate_Click
, btnDelete_Click
, and btnSearch_Click
.
Through the crud c# example, i showed you the simple way to insert update delete data from datagridview in c# windows forms application.
- Insert Update Delete and View data from SQL Database using ORM Lite in C#
- How to Insert Update Delete From Database in VB.NET
- How to Insert Update Delete and View data from SQL Database in C# using ADO.NET
- How to Insert Update Delete View data from SQL Database in C#
- Windows Forms: Insert Update Delete data in Database from DataGridView in C#
- Windows Forms: Insert Update Delete Search data from local database in C#
- Windows Forms: Insert Update Delete View data in SQL Server using 3 Tiers in C#
- Windows Forms: Insert Update Delete Select in SQL Server in C#