Windows Forms: Insert Update Delete Search Records in C# DataGridView

This post shows you How to Insert Update Delete and Search Records in C# DataGridView Windows Forms Application.

Creating a new Windows Forms Application project, then drag 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.

c# insert update delete search datagridview

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;

Creating an InitData method allows you to retrieve contact data from the contact table.

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;
}

Addting a click event handler to the Insert button allows you to insert data from textbox to contact table.

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.

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.

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))
            {
                if (cn.State == ConnectionState.Closed)
                    cn.Open();
                using (SqlCommand cmd = new SqlCommand("delete from contacts where Id = @Id", cn))
                {
                    cmd.Parameters.AddWithValue("Id", row.Cells[0].Value);
                    cmd.ExecuteNonQuery();
                    InitData();
                    Clear();
                }
            }
        }
    }
}

Adding a KeyPress event handler to the search textbox control allows you to catch the enter key.

private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        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;
        }
    }
}

Through the crud c# example, i showed you the simple way to insert update delete data from datagridview in c# windows forms application.