Click here to Skip to main content
16,020,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am trying to do the sum of value in textbox1 and textbox2 and result in textbox3.
sum is happening when application is debug from Visual studio, but when application deployed on web server, sum is not happening and getting error Input string was not in correct format.
Kindly help to get this solv

What I have tried:

C#
protected void TextBox16_TextChanged(object sender, EventArgs e)
        {
                if ((!string.IsNullOrEmpty(TextBox16.Text)) && (!string.IsNullOrEmpty(TextBox19.Text)))
                {
                TextBox30.Text = (Convert.ToDecimal(TextBox16.Text) + Convert.ToDecimal(TextBox19.Text)).ToString().Trim();
                }
}
Posted
Updated 4-Apr-16 19:38pm
v3
Comments
Abhipal Singh 5-Apr-16 1:40am    
Use try parse to convert string to decimal. It is possible that the input values are not decimals at all!.
Would you mind sharing the input?
P.S. trim() is not required.

1 solution

use TryParse [^]for casting the string to a numeric type

corrected code:
C#
if ((!string.IsNullOrEmpty(TextBox16.Text.Trim())) && (!string.IsNullOrEmpty(TextBox19.Text.Trim())))
{
    decimal a = 0, b = 0;
    if (decimal.TryParse(TextBox16.Text.Trim(), out a) && decimal.TryParse(TextBox19.Text.Trim(), out b))
        TextBox30.Text = (a + b).ToString();

}
 
Share this answer
 
Comments
Abhipal Singh 5-Apr-16 1:42am    
I think the null checks are not required if you are using try parse :) Just a word or advise.
Karthik_Mahalingam 5-Apr-16 1:49am    
yes Abhipal correct, i just edited his code.
but technically, if we do do the validation, the app performance will improve.
since the Tryparse will do lot of job inside( if exception arise ), compared to the simple validation outside.
Sergey Alexandrovich Kryukov 5-Apr-16 2:00am    
Wrong. Try parse doesn't throw and then handle exception, as you could imagine. It it does not run into exception at all. Look at the source code and you will see. Simple logic allows to suggest that your performance validation is also your fantasy. Sorry, but you have to reliably justify your statements.
—SA
Member 12256084 5-Apr-16 2:29am    
Karthik,
Your code is working fine and no error when application runs from web server, but When TextBox19 having decimal value like 10.00 hours and TextBox16 having numaric value like 10 hour, the sum is not happening in TextBox30.
Only when TextBox16 and TextBox19 having numaric value, the code is running as expected and sum is happening in textBox30.
Sergey Alexandrovich Kryukov 5-Apr-16 1:56am    
And assignment a = 0, b = 0 is totally redundant...
—SA

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