c# - DataGridView 验证旧值而不是新值

标签 c# validation datagridview

我有一个绑定(bind)到 DataTable 的 DataGridView,它有一个 double 列,值需要介于 0 和 1 之间。这是我的代码

private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index)
    {
        double percentage;
        if(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.GetType() == typeof(double))
            percentage = (double)dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value;
        else if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value.ToString(), out percentage))
        {
            e.Cancel = true;
            dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1";
            return;
        }
        if (percentage < 0 || percentage > 1)
        {
            e.Cancel = true;
            dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1";
        }
    }
}

然而,当 dgvImpRDP_InfinityRDPLogin_CellValidating 触发 dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value 时,我的问题将包含编辑前的旧值,而不是新值。

例如,假设旧值为 .1,我输入 3。以上代码在您退出单元格时运行,dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value 将为 < b>.1 对于该运行,代码验证数据并将 3 数据写入 DataTable。

我第二次点击它,尝试离开,这一次它表现得像它应该的那样,它会为单元格显示错误图标并阻止我离开。我尝试输入正确的值(例如 .7),但 Value 仍为 3,现在无法退出单元格,因为它因错误而被锁定,我的验证码将永远不要插入新的值(value)。

如有任何建议,我们将不胜感激。

编辑—— 新版本的代码基于 Stuart 的建议并模仿了 MSDN 文章使用的风格。仍然表现相同。

private void dgvImpRDP_InfinityRDPLogin_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == dtxtPercentageOfUsersAllowed.Index)
    {
        dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = String.Empty;
        double percentage;
        if (!double.TryParse(dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].FormattedValue.ToString(), out percentage) || percentage < 0 || percentage > 1)
        {
            e.Cancel = true;
            dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].ErrorText = "The value must be between 0 and 1";
            return;
        }
    }
}

最佳答案

您需要使用 DataGridViewCellValidatingEventArgs 实例的 FormattedValue 属性而不是单元格值,因为在验证成功之前单元格值不会更新:

The text entered by the user through the user interface (UI) becomes the FormattedValue property value. This is the value that you can validate before it is parsed into the cell Value property value. (MSDN)

关于c# - DataGridView 验证旧值而不是新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2819988/

相关文章:

c# - 在数据 GridView 中显示列表框

c# - 将字体更改为 DataGridView 行在 WinForms C# 中不起作用

c# - UpdatePanel、ModalPopupExtender 和输入按键问题

c# - 您将如何在 Java 或 C# 中编写高效的循环缓冲区?

c# - 异步使用 WinSCP .NET

c# - WPF、C# 中组合框的 DisplayMemberPath

javascript - 按照 tab-index 的顺序循环 jQuery 选择

javascript - 正则表达式可选和组

jquery - 计算非空输入字段[]?

c# - 使用对象列表填充 datagridview