You could subscribe to the CellClick
event and test the value e.ColumnIndex
:
if (e.ColumnIndex == -1)
{
dataGridView1.Rows.RemoveAt(e.RowIndex);
}
Or you could subscribe to the CellDoubleClick
event (using the same code) if you wanted to be a little more sure they didn't accidentally delete rows.
Since you have a button you want to use, I'd say try this:
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentCell.ColumnIndex == -1)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
}
But for some reason, it always returns 0 for CurrentCell.ColumnIndex
, even if you selected the row header.
I suppose you could still subscribe to the CellClick
event, but just store the current row index in a class-level variable that you can test in the button:
private bool isRowHeaderSelected = false;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
isRowHeaderSelected = (e.ColumnIndex == -1);
}
private void deleteRowButton(object sender, EventArgs e)
{
if (isRowHeaderSelected)
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentCell.RowIndex);
}