Reputation: 3292
private void deleteRowButton(object sender, EventArgs e)
{
if (dataGridView1.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentCell.RowIndex);
}
}
So this is what I've tried. Now without the if statement it would work but it will delete the row on the selected cell. I don't want the user to accidentally delete it. How do I make it so that it can delete the row if the user selects the row header?
Like this:
Upvotes: 0
Views: 896
Reputation: 66511
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);
}
Upvotes: 2
Reputation: 1803
I am guessing that you are writing winforms. Why don't you put the delete behind a messageBox? What datagridview event are you putting this under?
if (e.ColumnIndex == -1)
{
DialogResult dr = MessageBox.Show("Are you sure that you want to delete", "Are you sure?", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.Rows[e.RowIndex]);
}
}
Upvotes: 1