I have a DataGridView bound to a DataTable. I added a DataGridViewButtonColumn that serves as the delete button for the row.
Since it is bound to a DataTable, I'd like to be able to get the object of the row with the delete button clicked so I can delete it from the DataTable and then refresh the DataGrid.
This is how my button is setup:
var colDelete = new DataGridViewButtonColumn();
colDelete.Name = "DeleteButton";
colDelete.HeaderText = "Delete";
colDelete.Text = "Delete";
colDelete.UseColumnTextForButtonValue = true;
colDelete.DataPropertyName = "EthnicityDetailID";
colDelete.DisplayIndex = 10;
dataGridEthnicityData.Columns.Add(colDelete);
This is how I'm planning to handle the button click event:
private void dataGridEthnicityData_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.ColumnIndex == senderGrid.Columns["DeleteButton"].Index)
{
//ethnicityDataTable.Rows.RemoveAt(e.RowIndex);
dataGridEthnicityData.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error deleting ethnicity data: " + ex.Message + " " + ex.StackTrace);
}
}
How do I assign EthnicityDetailID as the value for the button and how do I retrieve the row with the button clicked as an object so I can retrieve the value and delete accordingly in the datatable?
Thank you.