I want to calculate the value of 3 cells in DATAGRIDVIEW
the calculation :
SDI = ((result - mean ) / SD)
I tried the following code :
private void dgvResult_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string result = dgvResult.CurrentRow.Cells[5].Value.ToString();
string mean = dgvResult.CurrentRow.Cells[6].Value.ToString();
string sd = dgvResult.CurrentRow.Cells[7].Value.ToString();
dgvResult.CurrentRow.Cells[16].Value = (Convert.ToDecimal(result) - Convert.ToDecimal(mean)) ;
// dgvResult.CurrentRow.Cells[8].Value = (Convert.ToDecimal(dgvResult.CurrentRow.Cells[16].Value.ToString()) / Convert.ToDecimal(sd));
}
This line of code working correct and calculate first part :
dgvResult.CurrentRow.Cells[16].Value = (Convert.ToDecimal(result) - Convert.ToDecimal(mean)) ;
result - mean
But the error appeared when added the last line of code
when type the number in the mean cell error appeared
but when i remove the last line of code and type numbers in the mean field its calculating the value
dgvResult.CurrentRow.Cells[8].Value = (Convert.ToDecimal(dgvResult.CurrentRow.Cells[16].Value.ToString()) / Convert.ToDecimal(sd));
How to solve this error please ?
CodePudding user response:
This error can occur because of different reasons, but I suggest you to:
- Check if the input strings are acceptable by the function.
- Even if the input strings are acceptable for conversion, the decimal you are trying to convert could be too big or too small, or precisions could be the problem, check if you exceed the limits.
I also suggest using Decimal.TryParse, it'll make your code more durable.
CodePudding user response:
You should first make sure that your string is really convertible to decimal. It seems that sd
is not convertible to decimal.
To check this, you can use Decimal.TryParse
. And one more thing it's better to check sd
before dividing, it should not be ZERO.