How can I convert String to Int?

1,733,779

Solution 1

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN

Solution 2

Convert.ToInt32( TextBoxD1.Text );

Use this if you feel confident that the contents of the text box is a valid int. A safer option is

int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

This will provide you with some default value you can use. Int32.TryParse also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if statement.

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}

Solution 3

int.TryParse()

It won't throw if the text is not numeric.

Solution 4

int myInt = int.Parse(TextBoxD1.Text)

Another way would be:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

The difference between the two is that the first one would throw an exception if the value in your textbox can't be converted, whereas the second one would just return false.

Solution 5

You need to parse the string, and you also need to ensure that it is truly in the format of an integer.

The easiest way is this:

int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
   // Code for if the string was valid
}
else
{
   // Code for if the string was invalid
}
Share:
1,733,779
turki2009
Author by

turki2009

Updated on July 08, 2022

Comments

  • turki2009
    turki2009 almost 2 years

    I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

    How can I do this?