-2

C# CODE I have a problem with my "Check in" form. I want to multiply the txtsubtotal and txtadvancepayment. In textchange if I put number on the txtadvancepayment, the overallresult is correct. But if I clear the txtadvancepayment (Incase when the user puts a wrong value) it would be error. The error says "Input string was not in a correct format." What should I do?

My Code downward

int overalltotal = 0;
              int a = Convert.ToInt32(txtsubtotal.Text);      
              int b = Convert.ToInt32(txtadvancepayment.Text);      
              overalltotal = a - b;      
              txttotalbalance.Text = overalltotal.ToString();
Jacob0825
  • 1
  • 2
  • Use `tryParse` here `Convert.ToInt32(txtadvancepayment.Text)` insted of `Convert.ToInt32` – Sushant Yelpale Dec 07 '19 at 01:45
  • please look up other posts on how to validate and convert text to number. Your number string is not all numbers and because of that you are getting the errors. – Jawad Dec 07 '19 at 02:06

2 Answers2

1

An empty string cannot be parsed as an int. As others have mentioned, you can use int.TryParse which accepts a string as the first parameter and an out int as the second parameter, which holds the parsed value. You could do this:

int overallTotal = 0;
int a = 0;
int b = 0;

// TryParse returns a bool
// If either of these fails, the variable a or b will keep the default 0 value
int.TryParse(txtSubtotal.Text, out a);
int.TryParse(txtAdvancePayment.Text, out b);

// Sum a and b
overallTotal = a + b;

If you want to show an error to the user that one or both fields isn't a valid integer, you can assign a bool variable such as var aIsNumber = int.TryParse(...) and then check if aIsNumber or bIsNumber is false. If so, then a and/or b could not be parsed to an int.

Matt U
  • 4,970
  • 9
  • 28
0

You could use Int32.TryParse.

Int32.Parse attempts to convert the string representation of a number to its 32-bit signed integer equivalent and returns value indicates whether the operation succeeded. This would mean, in case your textbox is empty or contains a invalid numeric representation, and the method would return false since it would not be able to convert it to int32

For example

  if(Int32.TryParse(txtsubtotal.Text,out var a) 
                   && Int32.TryParse(txtadvancepayment.Text,out var b))
  {
         // Code which requires a and b  
  } 
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51