我有一个DataGridView控件,它绑定了一个DataTable对象,其中有一列是双精度浮点型,其值必须在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
将为该运行提供.1,代码验证并将数据写入DataTable中的3。
我第二次点击它,试图离开,这次它的行为就像它应该的那样,它为单元格引发错误图标并防止我离开。我试图输入正确的值(比如.7),但Value
仍然是3,因为由于错误而锁定了单元格,并且我的验证代码永远不会推送新值。
任何建议都将不胜感激。
编辑-- 根据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;
}
}
}
dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].FormattedValue
的值是".1"。 - Scott Chamberlain