user1097772
user1097772

Reputation: 3549

Exception while converting String to integer in C#


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 :(

Upvotes: 4

Views: 19784

Answers (3)

Curtis
Curtis

Reputation: 5892

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...)

Upvotes: 2

user1108948
user1108948

Reputation:

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);
  }
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191048

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

Upvotes: 10

Related Questions