【问题标题】:DataGridView Cell value not available for validation when inserting a new row插入新行时,DataGridView 单元格值不可用于验证
【发布时间】:2015-08-19 11:19:52
【问题描述】:

情况:

我正在用 .NET4.0 在 VS2013 中使用 C# 编写一个 Winforms 应用程序。

为了在 DataGridView 中执行单元格级别验证,我处理了 CellValidating 事件。验证时,我使用

访问用户输入值
dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value

对于现有行的验证,这很好。

问题:

当用户在 new 行的单元格中键入内容,然后按下(例如,tab)移动到下一个单元格时,CellValidating 事件会触发,但 Value 始终包含 null。

问题:

在这些情况下,我如何访问用户输入的内容?我在想我应该在验证之前使用 EndEdit,但我认为 CellValidating 本质上是一个“编辑时”事件。

编辑

验证发生在一个验证器类中,其顶端如下所示:

    public void ValidateCell(string tableName, DataGridView dataGrid, DataGridViewCellValidatingEventArgs e, ColumnCatalogue columnCatalogue)
    {
        if (!(dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null || 
              dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == DBNull.Value ||
              string.IsNullOrWhiteSpace(dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
            )
        {
            ColumnDetails columnDetails = columnCatalogue.GetColumnDetails(tableName, dataGrid.Columns[e.ColumnIndex].Name);

            switch (columnDetails.DataType)
            {
                case "currency":
                    this.ValidateCurrency(dataGrid, columnDetails, e);
                    break;
                case "date":
                    this.ValidateDate(dataGrid, columnDetails, e);
                    break;
                case "email":
                    this.ValidateEmail(dataGrid, columnDetails, e);
                    break;
                case "int":
                    this.ValidateInt(dataGrid, columnDetails, e);
                    break;
                case "phone":
                    this.ValidatePhone(dataGrid, columnDetails, e);
                    break;
                case "postcode":
                    this.ValidatePostcode(dataGrid, columnDetails, e);
                    break;
                default:
                    break;
            } 
        }
    }

【问题讨论】:

  • 你能发布完整验证方法的代码吗?
  • @JustinRusso 现在添加

标签: c# validation datagridview


【解决方案1】:

由于数据尚未经过验证,它们不能位于CellValue 字段中。

相反,用户输入的输入都在Cell..的EditedFormattedValue字段中:

dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue

..和参数e..的FormattedValue字段:

e.FormattedValue

请注意,在(通常)作为字符串输入TextBox 编辑控件之后,两者都是object 类型。

另请注意,对于现有的和已填充的单元格,测试其Value 字段实际上是在测试旧的、未编辑的 值!因此,对于插入的行,您不会只对 Value 有问题,所有行都有问题!

【讨论】:

  • 这一切都说得通。现在工作完美无缺。感谢您抽出宝贵时间提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多