snippetcsharpCritical
How can I convert String to Int?
Viewed 0 times
howintconvertcanstring
Problem
I have a
How can I do this?
TextBoxD1.Text and I want to convert it to an int to store it in a database. How can I do this?
Solution
Try this:
or better yet:
Also, since
If you are curious, the difference between
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
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
Code Snippets
int x = Int32.Parse(TextBoxD1.Text);int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}Context
Stack Overflow Q#1019793, score: 1350
Revisions (0)
No revisions yet.