Following is solution Deleting a record via Delete button or by clicking keyboard delete button for selected row
private void Form1_Load(object sender, EventArgs e)
{
this.dgview.CellClick += new DataGridViewCellEventHandler(this.dgview_CellClick);
this.dgview.UserDeletingRow += dgview_UserDeletingRow;
loadData();
}
private void loadData()
{
try
{
DataTable dt =new DataTable();
DataColumn dc;
dc=new DataColumn("ID", typeof(int));
dt.Columns.Add(dc);
dc=new DataColumn("FirstName", typeof(string));
dt.Columns.Add(dc);
dc=new DataColumn("LastName", typeof(string));
dt.Columns.Add(dc);
dt.Rows.Add(1,"Ali","khan");
dt.Rows.Add(1,"Affan","raja");
dt.Rows.Add(1,"Amjad","marwat");
dt.Rows.Add(1,"Zohaib","awan");
dgview.DataSource = dt;
foreach (DataGridViewColumn column in dgview.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
}
if (dt.Rows.Count > 0)
{
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dgview.Columns.Add(btn);
btn.HeaderText = "Delete";
btn.Text = "Delete";
btn.Name = "btnDelete";
btn.UseColumnTextForButtonValue = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
// this can work when you press delete button in gridview at columIndex=3
private void dgview_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
dgview.Rows.RemoveAt(e.RowIndex);
int ID = Convert.ToInt32(dgview.Rows[e.RowIndex].Cells["ID"].Value.ToString());
}
}
// This can work when select a row and clicking delete key from keyboard
private void dgview_UserDeletingRow(object sender,DataGridViewRowCancelEventArgs e)
{
DialogResult response = MessageBox.Show("Are you sure you want to delete this row?", "Delete row?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if ((response == DialogResult.No))
{
e.Cancel = true;
}
else
{
}
}