Sco*_*ain 5 c# validation datagridview
我有一个绑定到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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我在dgvImpRDP_InfinityRDPLogin_CellValidating火灾时的问题dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value将包含编辑前的旧值,而不是新值.
例如可以说旧值是1.1和我进入3,上面的代码,当你退出电池,并运行dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value将是0.1该运行,代码验证和写入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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5971 次 |
| 最近记录: |