【问题标题】:How to validate each cell value when pasting values in DataGridView in Winforms?在 Winforms 中的 DataGridView 中粘贴值时如何验证每个单元格值?
【发布时间】:2018-06-14 04:35:48
【问题描述】:

我有一个 10 行和 5 列的 DataGridView。当我选择一行并将其粘贴到 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 事件吗?

【问题讨论】:

  • 推测复制的数据已经过验证,那么如果新行相同,为什么还需要验证呢?只有失去焦点才会引发该事件,因此您可能会想出一些乱七八糟的技巧来依次将焦点设置在每个单元格上。

标签: c# winforms datagridview copy-paste


【解决方案1】:

CellValidating/RowValidating 事件取决于焦点

备注 当您使用键盘(TAB、SHIFT+TAB 等)、调用 Selector 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多