I have added a checkbox column to the DataGridView and then written the following code
Namespalces
using System.Data;
using System.Data.SqlClient;
Code
public partial class Form1 : Form
{
private const string ConnectionString = @"Data Source=.\SQL2008R2;Initial Catalog=AjaxSamples;User id = sa;password=pass@123";
public Form1()
{
InitializeComponent();
BindGrid();
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//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[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";
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Name = "checkBoxColumn";
dataGridView1.Columns.Insert(0, checkBoxColumn);
dataGridView1.DataSource = dt;
}
}
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["checkBoxColumn"].Value))
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CustomerId", row.Cells["CustomerId"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
Table
DataGridView
