如何使用添加操作添加带有文本框值的十进制值并存储在textbox .text中? [英] How to add decimal value with textbox value always using addition operation and store in textbox .text?

查看:79
本文介绍了如何使用添加操作添加带有文本框值的十进制值并存储在textbox .text中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用文本框值添加十进制值并将其存储为相同的文本框文本。

问题是我得到异常输入字符串无效

或者其它concatinating但它没有执行加法操作。我是否会执行加法操作。如果你知道这一点,你会告诉我。



我试过的:



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();


      }

推荐答案

C#是一种强类型语言,所以你可以不要将十进制类型添加到字符串类型。您需要将输入从字符串转换为小数。幸运的是在.NET中很容易。



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
   }
}





另请参阅标准数字格式字符串| Microsoft Docs [ ^ ]


您好,



您在这里提到了两个问题。

1)当输入字符串无效时抛出异常。

2)不执行添加而是连接。



以下是这两个问题的解决方案。



1)为避免异常,您需要确保文本框值是有效的数值。你怎么做到这一点?好吧,有很多方法,但最好是使用.TryParse方法如下。



十进制值;

var isValid = decimal.TryParse( textbox1.Text,out value)
如果文本框文本是有效的数值,
isValid将为真。



2)在C#中, +运算符有两个含义。一个是添加,另一个是连接。现在,如果操作数中的任何一个是字符串,它将进行串联,将另一个操作数转换为字符串。

在您的情况下,使用值变量,如果十进制转换成功,则会设置该值。



希望这会有所帮助。



Sanjay
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


这篇关于如何使用添加操作添加带有文本框值的十进制值并存储在textbox .text中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆