int x = int.Parse("123");
How do i convert numbers in string format to int in c#?
You would use the Int32.Parse() method; however, this method will throw an exception if the string that is passed to it is not a valid sequence of characters that defines an integer.
One thing I like to do (and this method can be overloaded since it differs by parameter type as well as return type) is to take a string and an second parameter as a default value if it fails. You would then have something like:
int GetValue(string data, int defaultValue)
{
int result = defaultValue;
try { result = Int32.Parse(data); }
catch { }
return result;
}
Reply:Something like this should work for you
public int convertStringToInt(string strSource)
{
try
{
return int.Parse(strSource);
}
catch
{
return null;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment