I have a DataGridView bound to a DataTable, it has a column that is double, and the values should be between 0 and 1. Here is my code
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";
}
}
}
However, my problem, when it dgvImpRDP_InfinityRDPLogin_CellValidatingworks dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Value, will contain the old value before editing, and not the new value.
For example, let's say that the old value was .1, and I enter 3. The above code runs when you exit the cell, and there dgvImpRDP_InfinityRDPLogin[e.ColumnIndex, e.RowIndex].Valuewill be .1 for this start, the code checks and writes data 3 to the 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;
}
}
}