Exception when converting String to integer in C #


I get the error: The format correction was raw, the input line was not in the correct format.
for this line:

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

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

I really don't see the problem :(

+2
source share
3 answers

You really have to use int.TryParse. It is much easier to convert and you will not get exceptions.

+8
source

, . .Trim() . TryParse int ( ),

:

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

TryParse , , . (0 ...)

+1

Try using 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);
  }
}
0
source

All Articles