Alex Rivera | Logout

How can I convert String to Int?

Asked 2009-06-19T20:02:43.877
854

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?

Edit
Report

3 Answers

42
int.TryParse()

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

answered 2009-06-19T20:05:05.697
30
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.

answered 2009-06-19T20:08:03.320
17

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
}
answered 2009-06-19T20:06:36.910

Your Answer