【问题标题】:Why is the Tryparse not working and instantly throwing the catch?为什么 Tryparse 不工作并立即抛出捕获?
【发布时间】:2018-10-06 23:49:04
【问题描述】:

结果不会出现在我的结果文本框中,一旦我在第一号中输入任何内容,它就会立即给我“第二号无效”的提示。我很新,不明白为什么它不起作用。

namespace ShippingCalculator_BradleyH
{
    public partial class Form1: Form
    {
        double total;

        public Form1()
        {
            InitializeComponent();
        }

        private void Calculate_Click(object sender, EventArgs e)
        {
        }

        private void Number1_TextChanged(object sender, EventArgs e)
        {
            //assigning variables
            double num1;
            double num2;
            double result;

            //making sure numbers 1 and 2 are numbers.
            if (double.TryParse(Number1.Text, out num1))
            {
                if (double.TryParse(Number2.Text, out num2))
                {
                    result = num1 * num2;
                    Result.Text = result.ToString();
                }
                else
                {
                    MessageBox.Show("Number 2 is invalid.");
                }
            }
            else
            {
                MessageBox.Show("Number 1 is invalid.");
            }
        }
    }
}

【问题讨论】:

    标签: c# tryparse


    【解决方案1】:

    我假设两个文本框最初都是空的。只要您在Number1 中输入内容,此代码就会运行,而Number2 将为空。空字符串是无效的double,因此TryParse 将返回false

    以下是我的建议:

    • 首先,将此逻辑提取到一个单独的函数中。称它为 UpdateResult 或类似名称。
    • Number1_TextChangedNumber2_TextChanged 调用此函数
    • UpdateResult 中,应用以下逻辑:
      • 如果Number1.TextNumber2.Text 是空字符串,则将Result.Text 设置为空字符串。
      • 否则,请执行您现有的逻辑。

    【讨论】:

    • 我发现了我的问题,我没有意识到我放置的所有代码都在 Number1.Textbox 下,而不是我的计算按钮下。但是谢谢乔纳森!
    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多