To convert a string to int, use Int32.Parse
or Int32.TryParse
or Convert.ToInt32
int firstNumber = Int32.Parse(firstNumberTextBox.Text);
//throws exception if not convertible
or
int firstNumber;
bool result = Int32.TryParse(firstNumberTextBox.Text, out firstNumber);
//return false if not convertible
or
int firstNumber;
result = Convert.ToInt32(firstNumberTextBox.Text);
//throws exception if not convertible
Using the Convert.ToInt32(String)
method is equivalent to passing value to the
Int32.Parse(String)
method. value is interpreted by using the
formatting conventions of the current thread culture.
If you prefer
not to handle an exception if the conversion fails, you can call the
Int32.TryParse
method instead. It returns a Boolean
value that
indicates whether the conversion succeeded or failed.
You can use int
instead of Int32
.
So in your case, it seems int.TryPars
better fits:
int firstNumber;
int secondNumber;
int thirdNumber;
int answer;
int.TryParse(firstNumberTextBox.Text, out firstNumber);
int.TryParse(secondNumberTextBox.Text, out secondNumber);
int.TryParse(thirdNumberTextBox.Text, out thirdNumber);
answer = firstNumber + secondNumber * thirdNumber;
MessageBox.Show(answer.ToString());