情况:
我正在使用 .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;
}
}
}
最佳答案
由于数据尚未经过验证,因此它们不能出现在 Cell
的 Value
字段中。
相反,用户输入的输入都在 Cell
的 EditedFormattedValue
字段中..:
dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue
..和参数e
的FormattedValue
字段..:
e.FormattedValue
请注意,两者都是 object
类型,在(通常)作为字符串输入到 TextBox
编辑控件之后。
另请注意,对于现有单元格和填充单元格,测试它们的Value
字段实际上是在测试旧的、未编辑的 值!因此,对于插入的行,您不会只对 Value
有问题,您对所有行都有问题!
关于c# - 插入新行时 DataGridView 单元格值不可用于验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650742/