In this article I will explain with an example, how to delete
DataGridView row on
DELETE Key Press (Keyboard Key) in
Windows Forms (WinForms) Application with C# and VB.Net.
Form Design
The Form consists of following control:
DataGridView – For displaying data.
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.
Finally, the DataGridView MultiSelect property has been set with FALSE, so that user can’t select multiple rows.
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].HeaderText = "Name";
dataGridView1.Columns[1].Name = "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;
//Allow single row selection.
dataGridView1.MultiSelect = false;
}
}
}
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal 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).HeaderText = "Name"
dataGridView1.Columns(1).Name = "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()
dataGridView1.DataSource = Nothing
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
'Allow single row selection.
dataGridView1.MultiSelect = False
End Using
End Using
End Using
End Sub
Deleting selected Row of DataGridView in C# and VB.Net
The DELETE operation will be performed on 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 pressed the DELETE key and DeleteRow (explained later) method is called.
C#
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
this.DeleteRow();
}
}
VB.Net
Private Sub OnKeyDown(sender As Object, e As KeyEventArgs) Handles dataGridView1.KeyDown
If e.KeyCode = Keys.Delete Then
Me.DeleteRow()
End If
End Sub
DeleteRow
Inside the
DeleteRow method, the selected
DataGridView row is referenced and 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 DeleteRow()
{
//Reference the selected DataGridView row.
DataGridViewRow row = dataGridView1.SelectedRows[0];
//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 DeleteRow()
'Reference the selected DataGridView row.
Dim row As DataGridViewRow = dataGridView1.SelectedRows(0)
'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
End Sub
Screenshot
Downloads