Click here to Skip to main content
14,486,686 members
Rate this:
Please Sign up or sign in to 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
Page 1 of 2

Rate this:
Please Sign up or sign in to vote.

Solution 1

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[^]
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

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
   
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.
Page 1 of 2
1 2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100