Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to add decimal value with textbox value and store it it as same textbox text.
the problem is iam getting exceptions input string was invalid
or else its concatinating but its not performing the addition operation.how do i perform addition operation .hope you will tell me if you one know this .

What I have tried:

public void GETEXTRABEDCOST(int APPLY,Decimal EXTCOST)
      {

          decimal COST =( APPLY * EXTCOST);

          txtextrabedcost.Text =txtextrabedcost.Text+ COST .ToString();


      }
Posted
Updated 12-Mar-20 5:16am
Comments
F-ES Sitecore 10-Jul-17 8:43am    
Use Decimal.TryParse to convert txtextrabedcost.Text to a decimal, then add COST to that decimal and set txtextrabedcost.Text to the result of that addition converted ToString

C# is a strongly typed language so you can't add decimal types to string types. You need to convert your input from a string to a decimal. Luckily in .NET that's pretty easy.

public void GETEXTRABEDCOST(int APPLY, Decimal EXTCOST)
{
   decimal COST = APPLY * EXTCOST;
   decimal currentValue;
   if (decimal.TryParse(txtextrabedcost.Text, out currentValue))
   {
      // Choose the formatting option that suits you needs..
      txtextrabedcost.Text = string.Format("{0:0.00}", currentValue + COST);
   }
   else
   {
      // Error handling
   }
}


See also Standard Numeric Format Strings | Microsoft Docs[^]
 
Share this answer
 
v2
Hi,

You have mentioned two problems here.
1) It's throwing an exception when the input string is not valid.
2) Not performing addition but rather does concatenation.

Here is the solutions for both of these issues.

1) To avoid the exception you need to make sure that the textbox value is a valid numeric value. How do you do this? Well, so many ways but best is to use .TryParse method as below.

decimal value;
var isValid = decimal.TryParse(textbox1.Text, out value)
isValid will be true if the textbox text is a valid numeric value.

2) In C#, + operator has two meanings. One is to do addition and second do concatenation. Now, if it has any one of the operand is string, it will do concatenation converting the other operand to string.
In your situation, use value variable which gets set if the decimal conversion was successful.

Hope this helps.

Sanjay
 
Share this answer
 
Comments
saimanisha 15-Jul-17 22:34pm    
yeah i tried by converting text format to decimal and added two decimals then converted to text format and attached to textbox text.

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