DatagridView:如何删除选定的单元格

时间:2015-12-21 20:48:23

标签: c# .net winforms datagridview bindingsource

这里有很多关于如何删除所选行的问题,但没有关于如何删除所选单元格的问题。也就是说,我希望用户能够从不同的行和不同的列中选择单元格,并能够删除内容。我目前所拥有的是:

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。

目标

我想模拟行删除行为,您可以在其中选择行,按删除键,然后该行的所有单元格内容都保留为空白。我想这样做,而不是在细胞中留下零。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

要隐藏零,请尝试使用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;
  }
}

答案 1 :(得分:0)

请使用以下代码:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {
            cell.Value = "";
        }
        e.Handled = true;
    }
}
相关问题