Hello friends, In this tutorial, I am going to show an example of How to Delete Selected Row from DataGridView and Database in C# Windows Application.

Delete Selected Row from DataGridView and Database in C# Windows Application:

We are familiar with how to Bind Records from Database to DataGridView in C#. In this tutorial, we will see how to Delete Selected Row of DataGridView from Database in C#.

Create Database and Tables in SQL Server:

CREATE DATABASE [Debugonweb]

USE [Debugonweb]


GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [bigint] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](50) NULL,
[Gender] [varchar](10) NULL,
[Address] [varchar](50) NULL,
[State] [varchar](50) NULL,
[City] [varchar](50) NULL,
[Status] [varchar](20) NULL,
CONSTRAINT [PK__Employee__3214EC274AA9A371] PRIMARY KEY CLUSTERED 
(
[EmployeeID] 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

Insert Records:

USE [Debugonweb]
GO
SET IDENTITY_INSERT [dbo].[Employee] ON

GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (1, N'Vinod', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (2, N'Manoj', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (3, N'Ansh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (4, N'Ritesh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (5, N'Vishwas', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (6, N'Ansh', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (7, N'Varali', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (8, N'Nitin', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (9, N'Vikas', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (10, N'Ritwik', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (11, N'Arohi', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Gender], [Address], [State], [City], [Status]) VALUES (12, N'Ketan', N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO

Create a Windows Application Project:

Step 1: Create a Windows Application Project called DeleteDataGridviewRow.

Step 2: Drag a DataGridView and Button on the windows form.

Delete Selected Row

Step 3: Double Click the Form and add the following namespaces on the Form1.cs class.

using System.Data;
using System.Data.SqlClient;

Step 4: Create a method that will Bind your Database Records to DataGridView.

public void BindDataGridView()
{
try
{
DataTable dtData = new DataTable();
using (SqlConnection dbCon = new SqlConnection("Data Source=your-datasource;Initial Catalog=Debugonweb;Integrated Security=true"))
{
using (SqlCommand cmdGetRecords = new SqlCommand("SELECT [EmployeeID],[EmployeeName],[Gender],[Address],[State],[City],[Status] FROM [dbo].[Employee]", dbCon))
{

if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open();
}
using (SqlDataReader drGetData = cmdGetRecords.ExecuteReader())
{
dtData.Load(drGetData);
}
dataGridView1.DataSource = dtData;
}
}
}
catch (Exception ex)
{


}
}

Step 4: Call the above method on Form Load method.

private void Form1_Load(object sender, EventArgs e)
{
BindDataGridView();
 
}

Step 5: Now Create a method that will delete your record from the database.

public bool DeleteEmployee(string sEmployeeID)
{
bool bFlag = false;
try
{
 
using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-CN5IQI9\\SQLEXPRESS;Initial Catalog=Debugonweb;Integrated Security=true"))
{
using (SqlCommand cmdDeleteEmployee = new SqlCommand("Delete FROM [dbo].[Employee] Where EmployeeID="+sEmployeeID, dbCon))
{

if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open();
}
cmdDeleteEmployee.ExecuteNonQuery();
bFlag = true;
 
}
}
}
catch (Exception ex)
{


}
return bFlag;
}

Step 6: Now Write the following code on Button Click event.

var confirmResult = MessageBox.Show("Are you sure to delete this record ??",
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
int iRowIndex = dataGridView1.CurrentCell.RowIndex;
string sEmployeeID = Convert.ToString(dataGridView1.Rows[iRowIndex].Cells[0].Value);
bool bFlag = DeleteEmployee(sEmployeeID);
if (bFlag)
{
MessageBox.Show("Record Deleted Successfully");
BindDataGridView();
}
else
{
MessageBox.Show("Something went wrong.");
}
}

Step 7: If you want to delete record on press of delete key then you need to write the following code on key down event of DataGridView.

if (e.KeyCode == Keys.Delete)
{
var confirmResult = MessageBox.Show("Are you sure to delete this record ??",
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
int iRowIndex = dataGridView1.CurrentCell.RowIndex;
string sEmployeeID = Convert.ToString(dataGridView1.Rows[iRowIndex].Cells[0].Value);
bool bFlag = DeleteEmployee(sEmployeeID);
if (bFlag)
{
MessageBox.Show("Record Deleted Successfully");
BindDataGridView();
}
else
{
MessageBox.Show("Something went wrong.");
}
}

}

Complete code for Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DeleteDataGridviewRow
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
BindDataGridView();
 
}
public void BindDataGridView()
{
try
{
DataTable dtData = new DataTable();
using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-CN5IQI9\\SQLEXPRESS;Initial Catalog=Debugonweb;Integrated Security=true"))
{
using (SqlCommand cmdGetRecords = new SqlCommand("SELECT [EmployeeID],[EmployeeName],[Gender],[Address],[State],[City],[Status] FROM [dbo].[Employee]", dbCon))
{

if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open();
}
using (SqlDataReader drGetData = cmdGetRecords.ExecuteReader())
{
dtData.Load(drGetData);
}
dataGridView1.DataSource = dtData;
}
}
}
catch (Exception ex)
{


}
}
private void button1_Click(object sender, EventArgs e)
{
var confirmResult = MessageBox.Show("Are you sure to delete this record ??",
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
int iRowIndex = dataGridView1.CurrentCell.RowIndex;
string sEmployeeID = Convert.ToString(dataGridView1.Rows[iRowIndex].Cells[0].Value);
bool bFlag = DeleteEmployee(sEmployeeID);
if (bFlag)
{
MessageBox.Show("Record Deleted Successfully");
BindDataGridView();
}
else
{
MessageBox.Show("Something went wrong.");
}
}

}
public bool DeleteEmployee(string sEmployeeID)
{
bool bFlag = false;
try
{
 
using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-CN5IQI9\\SQLEXPRESS;Initial Catalog=Debugonweb;Integrated Security=true"))
{
using (SqlCommand cmdDeleteEmployee = new SqlCommand("Delete FROM [dbo].[Employee] Where EmployeeID="+sEmployeeID, dbCon))
{

if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open();
}
cmdDeleteEmployee.ExecuteNonQuery();
bFlag = true;
 
}
}
}
catch (Exception ex)
{


}
return bFlag;
}

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
var confirmResult = MessageBox.Show("Are you sure to delete this record ??",
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
int iRowIndex = dataGridView1.CurrentCell.RowIndex;
string sEmployeeID = Convert.ToString(dataGridView1.Rows[iRowIndex].Cells[0].Value);
bool bFlag = DeleteEmployee(sEmployeeID);
if (bFlag)
{
MessageBox.Show("Record Deleted Successfully");
BindDataGridView();
}
else
{
MessageBox.Show("Something went wrong.");
}
}

}
}
}
}

Output:

Delete DataGridView Row

View More:

Conclusion:

I hope you would love this post. Your feedback and suggestions are appropriated. Please feel free to comment for any technical help.

Thank You.

Leave a Comment