在c#中添加数字
我有一个数字文本框,我需要将其值添加到另一个数字 我已经尝试过这段代码
String add = (mytextbox.Text + 2)
,但它将数字 2 添加为另一个字符,就像如果我的文本框的值为 13,结果将变为 132
i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
mytextbox.Text
的类型是字符串。您需要将其解析为数字才能执行整数算术,例如请注意,您可能希望使用 < code>int.TryParse 以便处理文本框内容不是整数的情况,而不必捕获异常。例如:
The type of
mytextbox.Text
is string. You need to parse it as a number in order to perform integer arithmetic, e.g.Note that you may wish to use
int.TryParse
in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:您需要将文本转换为整数才能进行计算。
You need to convert the text to an integer to do the calculation.
如果你想确保转换不会引发任何异常
if you want to make sure the conversion doesn't throw any exception
我更喜欢 TryPase,那么你知道回退将为零(或者你定义为 intValue 的默认值的任何内容)
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
您可以使用
int.Parse
方法将文本内容解析为整数:You can use the
int.Parse
method to parse the text content into an integer:其他人已经发布了最常见的答案,但只是为了给您提供替代方案,您可以使用属性来检索 TextBox 的整数值。
如果您需要多次重复使用整数,这可能是一个好方法:
然后您可以像这样使用该属性:
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
And then you can use the property like this: