Check this simple code:
Step 1 : add buttons in Form_Load Event
private void DataGridUpdate_Load(object sender, EventArgs e)
{
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
//Add update button
btn.HeaderText = "Click Data";
btn.Text = "Update";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Insert(0, btn);
//Add delete button
DataGridViewButtonColumn btnDelete = new DataGridViewButtonColumn();
btnDelete.HeaderText = "Click Data";
btnDelete.Text = "Delete";
btnDelete.Name = "btnDelete";
btnDelete.UseColumnTextForButtonValue = true;
}
Step 2 :And Implement the CellContentClick Event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
int columnIndex = e.ColumnIndex;
string city = this.dataGridView1.Rows[rowIndex].Cells["city"].Value.ToString();
string id = this.dataGridView1.Rows[rowIndex].Cells["empid"].Value.ToString();
if (e.ColumnIndex == 0)
{
SqlConnection conn = new SqlConnection("ConnectionSTring");
conn.Open();
SqlCommand comm = new SqlCommand("Update emp set city=@city where empid=@empid", conn);
comm.Parameters.AddWithValue("city", city);
comm.Parameters.AddWithValue("empid", id);
comm.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Updated!");
//Re-bind dataGridview
}
else if (e.ColumnIndex == 1)
{
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("Delete from emp where empid=@empid", conn);
comm.Parameters.AddWithValue("empid", id);
comm.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Deleted!");
//Re-bind dataGridview
}
}