Getting an error response using the sum function

When I get data from a datagridview into the following text fields, and the function is applied to it, I usually get the wrong result. I use the sum function and the answer that it provides in result.text is incorrect. Can anyone point out a problem in the following code?

public void addqty() { int a, b; bool isAValid = int.TryParse(val1.Text, out a); bool isBValid = int.TryParse(val2.Text, out b); result.Text = (a + b).ToString(); } 
+4
source share
4 answers

If val1 or val2 fails Parse, a or b will be 0. You need to make sure that they are real numbers and process them accordingly if not.

 int a, b; if (int.TryParse(val1.Text, out a) && int.TryParse(val2.Text, out b)) { result.Text = (a + b).ToString(); } else { //handle bad values } 
+3
source

It seems that you do not take into account what to do if A or B is IMPOSSIBLE. Right now, if A is valid and B is not, it will still return A. The same will be true for B. If these are not the functions you want, you may need to use a different code:

 if (isAValid && isBValid) {result.Text = (a + b).ToString();} 
+1
source

You do not check the results of isAValid and isBValid , so if any of them is not parsed, the value of a and / or b will be 0 . You will still see the result, but it may not be right.

+1
source

I have included a simple check for this function. You should always include null checks, parsing checks, etc. I suspect that either text box 1 or 2 sends some invalid data.

  public void addqty() { int a, b; if (!int.TryParse(val1.Text, out a) || int.TryParse(val2.Text, out b)) result.Text = "Can't convert variable a or variable b"; else result.Text = (a + b).ToString(); } textBox1.Text = string.IsNullOrEmpty(row.Cells["Serial #"].Value.ToString()) ? "0" : row.Cells["Serial #"].Value.ToString(); textBox2.Text = string.IsNullOrEmpty(row.Cells["Barcode"].Value.ToString()) ? "0" : row.Cells["Barcode"].Value.ToString(); textBox3.Text = string.IsNullOrEmpty(row.Cells["Quantity"].Value.ToString()) ? "0" : row.Cells["Quantity"].Value.ToString(); 
+1
source

Source: https://habr.com/ru/post/1501304/


All Articles