我有一个绑定到一个DataTable一个DataGridView,它有一个列,它是一个双和值需要在0和1之间。这里是我的代码DataGridView的验证旧值insted的新价值
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.1和我进入3,上面的代码,当你退出细胞和dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value
将0.1该运行运行,代码验证和写入数据到DataTable。
我再次点击它,尝试离开,这次它表现得像它应该的那样,它引发了单元格的错误图标,并阻止我离开。我尝试输入正确的值(比如.7),但Value
仍然是3,现在没有出路的单元格,因为它由于错误而被锁定,我的验证码永远不会推送新值。
任何建议将不胜感激。
编辑 - 新版本的代码基于斯图尔特的建议和模仿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' =” 0.1" 之后我已进入5 – 2010-05-12 15:06:20
不。你需要看看e.FormattedValue! – stuartd 2010-05-12 16:22:38
啊!谢谢我甚至没有注意到e中的格式化值。 – 2010-05-12 17:55:49