在C#中添加两个数字的问题 [英] Problem with adding two numbers in C#

查看:82
本文介绍了在C#中添加两个数字的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是两个文本框和一个标签。我使用TextChanged事件来添加数字。您输入textBox1中的第一个数字和textBox2中的第二个数字。只要在textBox2中输入数字,它就会添加数字,总和会显示在下面的标签中。但是当我从textBox2中删除数字时,程序停止工作,并显示'格式异常未处理。输入字符串的格式不正确。



I am using two textboxes and a label. I used the TextChanged event to add the numbers. You enter the first number in textBox1 and the second number in textBox2. As soon as you enter a number in textBox2 it adds the numbers and the sum appears in the label below. But when I delete the number from textBox2 the program stops working and this appears 'The format exception was unhandled. Input string was not in a correct format."

private void textBox2_TextChanged(object sender, EventArgs e)
        {
            double a = Double.Parse(textBox1.Text);
            double b = Double.Parse(textBox2.Text);
            
            label3.Text = "SUM: " + (a + b);

            
        }



如何解决这个问题?我希望它能添加数字,即使我从textBox2中删除了数字并输入一个新的数字(当程序运行时)。 < br $> b $ b

我尝试了什么:



我只尝试在线搜索解决方案,但我不是succ对此感到满意。几乎每次遇到问题,我都会在网上寻找解决方案。



Any tips on how am I supposed to find the solution to my next problem myself, instead of asking for help?

推荐答案

现在空字符串也是未定义的double值。使用double.TryParse而不是double.Parse。 Double.TryParse-Methode :( String,NumberStyles,IFormatProvider,Double)(系统) [ ^ ]

使用TryParse,您可以轻松地检测到用户输入真的是一个数字。

我希望这个帮助。
Now an empty string is also an undefined double value. Use double.TryParse instead of double.Parse.Double.TryParse-Methode: (String, NumberStyles, IFormatProvider, Double) (System)[^]
With TryParse you can easely detect wheter the user Input was really a number.
I hope this helps.


首先,在转换用户输入时不要使用Parse - 它们总是会出错,而Parse会抛出异常并导致应用程序崩溃。请改用tryParse:

Firstly, don't use Parse when converting user input - they always make mistakes, and Parse will throw an exception and crash your app. Use tryParse instead:
double a;
double b;
if (!Double.TryParse(textBox1.Text, out a))
   {
   ... Report problem to user or ignore it
   return;
   }
if (!Double.TryParse(textBox2.Text, out b))
   {
   ... Report problem to user or ignore it
   return;
   }

然后你可以添加它们并显示总数。有几种方法可以做到这一点:

Then you can add them and present the total. There are several ways to do that:

label3.Text = "SUM: " + (a + b).ToString();

这使用字符串连接,这不一定是个好主意。

This uses string concatenation, and that isn't necessarily a good idea.

label3.Text = string.Format("SUM: {0}", a + b);

这适用于任何C#版本。

double result = a + b;

This will work on any C# version.
double result = a + b;

label3.Text =


SUM:{result};

从C#V6开始工作。


这篇关于在C#中添加两个数字的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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