Search code examples
c#winformsdatagridviewcopy-paste

How to validate each cell value when pasting values in DataGridView in Winforms?


I have a DataGridView with 10 rows and 5 columns. When I select a row and paste it in the AddNewRow, the CellValidating event is not triggered for the cells. Below are my code to paste the copied values into the grid.

//Get the starting Cell
        DataGridViewCell startCell = GetStartCell(dataGridView1);
        //Get the clipboard value in a dictionary
        Dictionary<int, Dictionary<int, string>> cbValue =
                ClipBoardValues(Clipboard.GetText());

        int iRowIndex = startCell.RowIndex;
        foreach (int rowKey in cbValue.Keys)
        {
            int iColIndex = startCell.ColumnIndex;
            foreach (int cellKey in cbValue[rowKey].Keys)
            {
                //Check if the index is within the limit
                if (iColIndex <= dataGridView1.Columns.Count - 1
                && iRowIndex <= dataGridView1.Rows.Count - 1)
                {
                    DataGridViewCell cell = dataGridView1[iColIndex, iRowIndex];

                    //Copy to selected cells if 'chkPasteToSelectedCells' is checked
                    if (cell.Selected)
                        cell.Value = cbValue[rowKey][cellKey];
                }
                iColIndex++;
            }
            iRowIndex++;
        }

Is it the behavior of DataGridView that the cellValidating will not trigger for each cells when pasting the values in the grid?

Can we have trigger the cellValidation event for all the pasted cells while pasting is moved to next cell?


Solution

  • The CellValidating/RowValidating Events depend on the focus.

    Remarks When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Selector SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:

    1. Enter
    2. GotFocus
    3. Leave
    4. Validating
    5. Validated
    6. LostFocus

    See: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx