在 Winforms 的 DataGridView 中粘贴值时如何验证每个单元格值?

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

我有一个包含 10 行和 5 列的 DataGridView。当我 select 一行并将其粘贴到 AddNewRow 时,不会为单元格触发 CellValidating 事件。下面是我将复制的值粘贴到网格中的代码。

//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++;
        }

在网格中粘贴值时,cellValidating 不会针对每个单元格触发,这是 DataGridView 的行为吗?

我们能否在粘贴移动到下一个单元格时为所有粘贴的单元格触发 cellValidation 事件?

CellValidating/RowValidating事件取决于焦点

备注 当您使用键盘(TAB、SHIFT+TAB 等)、调用选择器 SelectNextControl 方法或将 ContainerControl.ActiveControl 属性 设置为当前窗体来更改焦点时,会发生焦点事件按以下顺序:

  1. 输入
  2. GotFocus
  3. 离开
  4. 正在验证
  5. 已验证
  6. 失焦

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