In this article I will explain with an example, how to delete multiple selected rows from DataGridView based on CheckBox selection in Windows Forms (WinForms) Application using 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.
Namespaces
You will need to import the following namespaces.
C#
using System.Linq;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Linq
Imports System.Data
Imports System.Data.SqlClient;
Binding DataGridView in C# and VB.Net
Inside the Form Load event handler, columns are added to the DataGridView and the BindGrid method (explained later) is called.
BindGrid
Inside the BindGrid method, records are fetched from Customers table and DataGridView is populated.
C#
private const string constr = @"Data Source=.\SQL2022;Initial Catalog=AjaxSamples;User id=sa;Password=pass@123";
private void Form1_Load(object sender, EventArgs e)
{
//Set Columns Count
dataGridView1.ColumnCount = 3;
//Hide the last blank line
dataGridView1.AllowUserToAddRows = false;
//Add Columns
dataGridView1.Columns[0].Name = "CustomerId";
dataGridView1.Columns[0].HeaderText = "CustomerId Id";
dataGridView1.Columns[0].DataPropertyName = "CustomerId";
dataGridView1.Columns[0].Width = 100;
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[1].Name = "Name";
dataGridView1.Columns[1].DataPropertyName = "Name";
dataGridView1.Columns[1].Width = 100;
dataGridView1.Columns[2].Name = "Country";
dataGridView1.Columns[2].HeaderText = "Country";
dataGridView1.Columns[2].DataPropertyName = "Country";
dataGridView1.Columns[2].Width = 100;
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 30;
checkBoxColumn.Name = "checkBoxColumn";
dataGridView1.Columns.Insert(0,checkBoxColumn);
this.BindGrid();
}
private void BindGrid()
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
VB.Net
Private Const constr As String = "Data Source=.\SQL2022;Initial Catalog=AjaxSamples;User id=sa;Password=pass@123"
Private Sub Form1_Load(sender As System.Object, e As EventArgs) Handles MyBase.Load
'Set Columns Count
dataGridView1.ColumnCount = 3
'Hide the last blank line
dataGridView1.AllowUserToAddRows = False
'Add Columns
dataGridView1.Columns(0).Name = "CustomerId"
dataGridView1.Columns(0).HeaderText = "CustomerId Id"
dataGridView1.Columns(0).DataPropertyName = "CustomerId"
dataGridView1.Columns(0).Width = 100
dataGridView1.Columns(1).HeaderText = "Name"
dataGridView1.Columns(1).Name = "Name"
dataGridView1.Columns(1).DataPropertyName = "Name"
dataGridView1.Columns(1).Width = 100
dataGridView1.Columns(2).Name = "Country"
dataGridView1.Columns(2).HeaderText = "Country"
dataGridView1.Columns(2).DataPropertyName = "Country"
dataGridView1.Columns(2).Width = 100
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = ""
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
dataGridView1.Columns.Insert(0,checkBoxColumn)
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sql, con)
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Using
End Sub
Deleting multiple rows from DataGridView using C# and VB.Net
When the Delete Button is clicked, all the selected rows of DataGridView are stored into a Generic List collection of DataGridViewRow class.
Then, a check is performed if the row is selected or not, if selected then a confirmation box is displayed and again a check is performed whether the No or Yes Button is clicked.
If Yes Button is clicked, then the CustomerId of the selected record is passed as parameter to SqlCommand class.
After that, ExecuteNonQuery method is executed which deletes the record from the Database table.
Finally, the BindGrid method (explained earlier) is called, which populates the DataGridView.
C#
private void OnDelete(object sender, EventArgs e)
{
List<DataGridViewRow>selectedRows = (from row in dataGridView1.Rows.Cast<DataGridViewRow>()
where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true
select row).ToList();
string sql = "DELETE FROM Customers WHERE CustomerId = @CustomerId";
if (selectedRows.Count > 0)
{
if (MessageBox.Show(string.Format("Do you want to delete {0} rows?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow row in selectedRows)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@CustomerId", row.Cells["CustomerId"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
thisthis.BindGrid();
}
}
else
{
MessageBox.Show("Please select row.");
}
}
VB.Net
Private Sub OnDelete(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim selectedRows As List(Of DataGridViewRow) = (From row In dataGridView1.Rows.Cast(Of DataGridViewRow)()
Where Convert.ToBoolean(row.Cells("checkBoxColumn").Value) = True).ToList()
Dim sql As String = "DELETE FROM Customers WHERE CustomerId = @CustomerId"
If selectedRows.Count > 0 Then
If MessageBox.Show(String.Format("Do you want to delete {0} rows?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
For Each row As DataGridViewRow In selectedRows
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@CustomerId", row.Cells("CustomerId").Value)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
Me.BindGrid()
End If
Else
MessageBox.Show("Please select row.")
End If
End Sub
Screenshot
Downloads