【发布时间】:2015-12-21 20:48:22
【问题描述】:
这里有很多关于如何删除选定行的问题,但没有关于如何删除选定单元格的问题。也就是说,我希望用户能够从不同的行和不同的列中选择单元格,并能够删除内容。我现在拥有的是:
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 分配给单元格内容。
目标
我想模拟行删除行为,您可以在其中选择一行,按下 delete 键,然后该行的所有单元格内容都保留为 空白。我想这样做,而不是在单元格中留下零。我该怎么做?
【问题讨论】:
标签: c# .net winforms datagridview bindingsource