【问题标题】:DatagridView: How to delete selected cellsDatagridView:如何删除选定的单元格
【发布时间】: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


    【解决方案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;
      }
    }
    

    【讨论】:

    • 嗯,我在加载数据时收到 InvalidCastException
    • @Iason 你说它们都是整数。如果没有,你必须考虑到这一点。
    • 我想我需要将 (int) 更改为 (double)。
    • 该代码适用于 (double),但它会在加载数据时删除任何明显包含 0 的单元格。
    • @Iason 然后你需要在某处存储一个标志以确定加载的零和删除的零之间的差异。
    【解决方案2】:

    请使用以下代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多