Search code examples
c#datagridviewcell

C# How to simultaneously select and delete the contents of two cells?


I would like to add the following functionality in my DataGridView, make it so that you can choose two or more cells only and delete their contents (maybe with a right click and then choose delete). Currently my implementation for the cell value changed event is:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        double currentCellValue;
        string PinInGrid = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        if (!double.TryParse(PinInGrid, out currentCellValue))
        {
            MessageBox.Show("Incorrect input!");
            DataTable dt = this.dataGridView1.DataSource as DataTable;
            dt.RejectChanges();
            return;
        }
    }

Is this possible?


Solution

  • This may be more appropriate as a comment, but I don't have sufficient privileges. Deleting the contents of multiple cells can be implemented like this:

        private void dgvItems_KeyDown(object sender, KeyEventArgs e)
        {
            var dgv = (DataGridView)sender;
    
            if(e.KeyCode == Keys.Delete)
            {
                foreach(DataGridViewCell cell in dgv.SelectedCells)
                {
                    if (!cell.ReadOnly)
                    {
                        cell.Value = "";
                    }
                }
            }
        } 
    

    This is triggered by selecting any number of cells and pressing 'delete', but the trigger can be anything you like. Depending on the data type of you cells you may need to change the cell.Value = "" line.

    See this question for an implementation of a right-click context menu with a delete option.