gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:19:07 26 4
gpt4 key购买 nike

我有一个绑定(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com