Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi there, is there some way of returning Zero (0) if int.TryParse() cannot return int

I have two text Boxes which i must check for numeric inputs using int.try Parse()
If one or both of my text Boxes contain strings or nulls other other than int values, i want to set their values to zero (0) and sum up the results
int number1=Convert.ToInt32(textBox1.Text);

int number2=Convert.ToInt32(textBox2.Text);

int sum = number1 + number2;
  
if number1=null  or "string" and number2 = null or "string"

sum=0+0;

Thanks in Advance
Yours Martin
Posted
Updated 18-Jul-11 22:46pm
v2

Try:
int val;
int i = int.TryParse(testBox1.Text, out val) ? val : 0;
 
Share this answer
 
Comments
Manfred Rudolf Bihy 19-Jul-11 4:37am    
Three nearly identical answers. I think I'll have to put my tinfoil hat on again ;).

My 5!
int number1 = (int.TryParse(textBox1.Text, out number1)) ? number1 : 0;
int number2 = (int.TryParse(textBox2.Text, out number2)) ? number2 : 0;
int sum = number1 + number2;


Cheers!

—MRB
 
Share this answer
 
Comments
Espen Harlinn 19-Jul-11 4:49am    
Neat, my 5
int a = 0;
int b = 0;
int.TryParse(textbox1.Text, out a);
int.TryParse(textbox2.Text, out b);
int sum = a + b;


TryParse will ninja it for you ;)
 
Share this answer
 
Comments
Manfred Rudolf Bihy 19-Jul-11 4:38am    
Good answer! 5+
Might helps,

C#
class Program
{
    static int ParseInt(string valueToParse)
    {
        int result;
        return int.TryParse(valueToParse, out result) ? result : result;
    }
    static void Main(string[] args)
    {
        int sum = ParseInt("H5") + ParseInt("5");
    }
}

:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900