Reputation: 249
There are number of questions on here about how to delete selected rows, but none about how to delete selected cells. That is, I would like for the user to be able to select cells from different rows and different columns, and be able to delete the contents. What I currenlty have is :
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
int rowIndex = cell.RowIndex;
int colIndex = cell.ColumnIndex;
dataGridView1.Rows[rowIndex].Cells[colIndex].Value = 0;
}
}
So the user has to select the required cells and then push the delete button(here I assumed all my columns are of numeric type, so 0 works). But it doesn't leave the cells completely empty. Here is another attempt:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && dataGridView1.CurrentCell.Selected)
{
dataGridView1.CurrentCell.Value = null;
e.Handled = true;
}
}
Unfortunately this event gets caught by my dataGridView1_DataError event, where I have
bindingSource1.CancelEdit();
And so I can't assign null to cell contents.
Goal
I would like to emulate the row delete behaviour, where you can select a row, push the delete key and then all cell contents of that row are left blank. I would like to do this, instead of leaving zeros in the cells. How can I do that?
Upvotes: 1
Views: 4963
Reputation: 31
Please use the following code:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
cell.Value = "";
}
e.Handled = true;
}
}
Upvotes: 3
Reputation: 81635
To hide the zeroes, try using the CellFormatting event:
void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.Value != null && e.Value.ToString() != "" && (int)e.Value == 0) {
e.Value = string.Empty;
e.FormattingApplied = true;
}
}
Upvotes: 1