In this article I will explain with an example, how to delete selected rows of DataGridView in Windows Forms (WinForms) Application with C# and VB.Net.
DataBase
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The Form consists of following controls:
DataGridView – For displaying data.
Button – For deleting rows.
The Button has been assigned with a Click event handler.
The DataGridView has been assigned with following event handler:
Events
KeyDown – For deleting records on DELETE key press.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Binding DataGridView in C# and VB.Net
Inside the Form Load event handler, columns are added to the DataGridView and the BindGrid method is called.
BindGrid
Inside the BindGrid method, records are fetched from Customers table and DataGridView is populated.
C#
private void Form1_Load(object sender, EventArgs e)
{
//Set AutoGenerateColumns False.
dataGridView1.AutoGenerateColumns = false;
//Set Columns Count.
dataGridView1.ColumnCount = 3;
//Add Columns.
dataGridView1.Columns[0].Name = "CustomerId";
dataGridView1.Columns[0].HeaderText = "Customer Id";
dataGridView1.Columns[0].DataPropertyName = "CustomerId";
dataGridView1.Columns[1].Name = "Name";
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[1].DataPropertyName = "Name";
dataGridView1.Columns[2].Name = "Country";
dataGridView1.Columns[2].HeaderText = "Country";
dataGridView1.Columns[2].DataPropertyName = "Country";
this.BindGrid();
}
private void BindGrid()
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Set AutoGenerateColumns False.
dataGridView1.AutoGenerateColumns = False
'Set Columns Count.
dataGridView1.ColumnCount = 3
'Add Columns.
dataGridView1.Columns(0).Name = "CustomerId"
dataGridView1.Columns(0).HeaderText = "Customer Id"
dataGridView1.Columns(0).DataPropertyName = "CustomerId"
dataGridView1.Columns(1).Name = "Name"
dataGridView1.Columns(1).HeaderText = "Name"
dataGridView1.Columns(1).DataPropertyName = "Name"
dataGridView1.Columns(2).Name = "Country"
dataGridView1.Columns(2).HeaderText = "Country"
dataGridView1.Columns(2).DataPropertyName = "Country"
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Deleting selected Rows of DataGridView in C# and VB.Net
The DELETE operation will be performed on Button click and on DELETE key press as well.
Button Click
When the Delete Button is clicked, DeleteRows method (explained later) is called.
DELETE key press
When the DELETE key on keyboard is pressed, the DataGridView KeyDown event handler is executed.
Inside the KeyDown event handler, a check is performed if the user press the DELETE key and DeleteRows method (explained later) is called.
DeleteRows method
Inside the DeleteRows method, a FOR EACH loop is executed over the DataGridView selected rows.
Inside the FOR EACH loop, the CustomerId is fetched from the DataGridView row.
Then, the SqlCommand class object is created where the SQL query is passed to it and based on CustomerId the record is deleted using ExecuteNonQuery method.
Finally, if the record is deleted then, the row is removed from DataGridView Row collection using Remove method.
C#
private void OnDelete(object sender, EventArgs e)
{
this.DeleteRows();
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
this.DeleteRows();
}
}
private void DeleteRows()
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//Fetch the CustomerId from the DataGridView row.
object customerId = row.Cells[0].Value;
int deleted = 0;
string sql = "DELETE FROM Customers WHERE CustomerId = @CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
con.Open();
deleted = cmd.ExecuteNonQuery();
con.Close();
}
}
if (deleted > 0)
{
dataGridView1.Rows.Remove(row);
}
}
}
VB.Net
Private Sub OnDelete(sender As Object, e As EventArgs) Handles btnDelete.Click
Me.DeleteRows()
End Sub
Private Sub OnKeyDown(sender As Object, e As KeyEventArgs) Handles dataGridView1.KeyDown
If e.KeyCode = Keys.Delete Then
Me.DeleteRows()
End If
End Sub
Private Sub DeleteRows()
ForEach row As DataGridViewRow In dataGridView1.SelectedRows
'Fetch the CustomerId from the DataGridView row.
Dim customerId As Object = row.Cells(0).Value
Dim deleted As Integer = 0
Dim sql As String = "DELETE FROM Customers WHERE CustomerId = @CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
con.Open()
deleted = cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
If deleted > 0 Then
dataGridView1.Rows.Remove(row)
End If
Next
End Sub
Screenshot
Downloads