4


I get error: Format exception was unhandled, Input string was not in a correct format.
for this line:

int right = System.Convert.ToInt32(rightAngleTB.Text);

rightAngleTB is TextBox, the value Text is "25" (without the "").

I really don´t see the problem :(

3
  • 4
    I would take a bet and say rightAngleTB.Text does not contain the text 25 Commented Apr 27, 2012 at 20:10
  • Are you sure that the value text is just 25? There aren't any extra characters in there, such as a decimal place, or extraneous whitespace? Convert.ToInt32 should definitely be able to convert a string of 25 to an int. Commented Apr 27, 2012 at 20:24
  • @BrokenGlass you´re right - I have that text box under label and I´ve unfortunately named the label with name rightAngleTB instead of the text box .. damn mistakes when you click on bad object :/ Commented Apr 27, 2012 at 20:33

3 Answers 3

10

You really should use int.TryParse. It is much easier to convert and you won't get exceptions.

Sign up to request clarification or add additional context in comments.

Comments

2

I notice quite often that users sometimes have leading or trailing spaces in their input. Using .Trim() will get rid of leading and trailing whitespace. Then the TryParse will give you an int (if the trimmed Text is an integer) without throwing an exception

Use the following:

int right = 0;  //Or you may want to set it to some other default value

if(!int.TryParse(rightAngleTB.Text.Trim(), out right))
{
    // Do some error handling here.. Maybe tell the user that data is invalid.
}

// do the rest of your coding..  

If the above TryParse failed, the value for right will be whatever you set it to in your declaration above. (0 in this case...)

Comments

1

Try the code below.

using System;

public class StringParsing
{
public static void Main()
{
  // get rightAngleTB.Text here
  TryToParse(rightAngleTB.Text);
}

private static void TryToParse(string value)
{
  int number;
  bool result = Int32.TryParse(value, out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Attempted conversion of '{0}' failed.", value);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.