DatagridView:如何删除所选单元格
本文关键字:选单 单元格 删除 何删除 DatagridView | 更新日期: 2023-09-27 18:27:35
这里有很多关于如何删除所选行的问题,但没有关于如何删除选定单元格的问题。也就是说,我希望用户能够从不同的行和列中选择单元格,并能够删除内容。我现在拥有的是:
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;
}
}
因此,用户必须选择所需的单元格,然后按下删除按钮(这里我假设我的所有列都是数字类型,所以0有效)。但它并没有让细胞完全空置。这是另一个尝试:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && dataGridView1.CurrentCell.Selected)
{
dataGridView1.CurrentCell.Value = null;
e.Handled = true;
}
}
不幸的是,这个事件被我的dataGridView1_DataError事件捕获,我有
bindingSource1.CancelEdit();
所以我不能为单元格内容指定null。
目标
我想模拟行删除行为,您可以选择一行,按下删除键,然后该行的所有单元格内容都保留为空白。我想这样做,而不是在单元格中留下零。我该怎么做?
要隐藏零,请尝试使用CellFormatting事件:
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;
}
}
请使用以下代码:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
cell.Value = "";
}
e.Handled = true;
}
}