Click here to Skip to main content
15,878,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I am using visual studio 2008
I have a form with two In Put text Boxes
I want to check whether the inputs are of type int, if they are, i sum up the value else, i just concatenate the two values(if they are of string types)

How can i achieve this?
Thanks in Advance
Yours faithfully
Martin
Posted

A bit weird requirement, but I hope this is just for training. If you use int.TryParse, it will return false if parsing is unsuccessful. Practically, this is the only reliable way to validate the string for parsing into integer. You can do it with any of the integer types.

—SA
 
Share this answer
 
v2
Comments
Tarun.K.S 15-Jul-11 10:33am    
That's right. 5+
Sergey Alexandrovich Kryukov 15-Jul-11 10:59am    
Thank you, Tarun.
--SA
Espen Harlinn 15-Jul-11 10:52am    
My 5, a nice reply as usual :)
Sergey Alexandrovich Kryukov 15-Jul-11 10:58am    
Thank you, Espen.
--SA
Try this way:

C#
void Add()
{
    int a, b;
    //Check for integer
    if (int.TryParse(textBox1.Text, out a) && int.TryParse(textBox2.Text, out b))
    {
        txtResult.Text = (a + b).ToString();
    }    
    // The value in textboxes are string
    else
    {
        txtResult.Text = textBox1.Text + textBox2.Text
    }
}


Hope this helps.
 
Share this answer
 
v2
Comments
Espen Harlinn 15-Jul-11 10:53am    
Nice reply, my 5
Tarun.K.S 15-Jul-11 13:08pm    
Thank you!
Take in both parameters as strings:
txtResult.Text = HandleInput(textbox1.Text, textbox2.Text);

public string HandleInput(string s1, string s2)
{
int i1;
int i2;
if (int.TryParse(s1, out i1) && int.TryParse(s2, out int2))
return (i1 + i2).ToString();
else
return s1 + s2;
}
 
Share this answer
 
v3
Comments
Tarun.K.S 15-Jul-11 10:33am    
After posting the answer I saw that you had already answered! :doh:
My 5 for the solution.
Espen Harlinn 15-Jul-11 10:53am    
Nice reply, my 5
Use the int.TryParse . If it returns true then its a integer .
 
Share this answer
 
Comments
Tarun.K.S 15-Jul-11 13:08pm    
You could have explained more, and I didn't downvote your 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