c# - 插入新行时 DataGridView 单元格值不可用于验证

标签 c# validation datagridview

情况:

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

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

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

对于现有行的验证,这工作正常。

问题:

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

问题:

在这些情况下,我如何访问用户输入的内容?我想我应该在验证之前结束编辑,但我认为 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;
            } 
        }
    }

最佳答案

由于数据尚未经过验证,因此它们不能出现在 CellValue 字段中。

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

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

..和参数eFormattedValue字段..:

e.FormattedValue

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

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

关于c# - 插入新行时 DataGridView 单元格值不可用于验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650742/

相关文章:

c# - 数据绑定(bind)后如何将图像设置为数据 GridView 单元格?

c# - 转换为字符串时精度下降到 3 位大数字

c# - 将特殊字符分配给字符串时,Razor 页面会弄乱编码

c# - 动态查询在 asp.net 中不起作用

asp.net - ASP .net 验证技术

c# - 数据绑定(bind) DataGridView 单元格格式 Int 到月份名称转换

c# - session 状态反模式(或一般的全局状态)

jquery - 具有实时验证功能的 HTML 5 表单插件?

python - 使用 DB 数据模型生成 SQLAlchemy 模型、模式和 JSON 响应

c# - 数据 GridView : DataGridViewImageColumn displays a red cross