【问题标题】:Format Exception was unhandled in C#格式异常在 C# 中未处理
【发布时间】:2016-10-19 05:51:09
【问题描述】:

我是这方面的初学者,如果可以的话,请解释一下到底发生了什么以及为什么?谢谢。我正在创建一个窗口表单来计算员工的总工资和佣金,同时考虑员工的类型、他们的工作时间以及他们获得的销售收入。例如,我输入 S 作为员工类型,工作时间为 30 小时,销售收入为 200。但我不断收到这个错误,我不知道为什么。

“'System.FormatException' 类型的未处理异常发生在 mscorlib.dll

附加信息:输入字符串的格式不正确。"

这个错误即将出现

decimal commission = Convert.ToDecimal(txtSalesCommission.Text);

特别是它指向(txtSalesCommission.Text)

这是它的代码。

private void btnCalculate_Click(object sender, EventArgs e)
{
            string employeeType = txtEmployeeType.Text;
            decimal hours = Convert.ToDecimal(txtHoursWorked.Text);
            decimal revenue = Convert.ToDecimal(txtSalesRevenue.Text);
            decimal commission = Convert.ToDecimal(txtSalesCommission.Text);
            decimal totalPay = Convert.ToDecimal(txtTotalPay.Text);

            txtSalesRevenue.Text = revenue.ToString("c");
            txtSalesCommission.Text = commission.ToString("c");
            txtTotalPay.Text = totalPay.ToString("c");

            //Employee Types: S   = Salaried Employees
            //                HC  = Hourly Commission Employees
            //                HNC = Hourly Non-Commission Employees  

            if (employeeType == "S")

            {
                totalPay = (300 + commission);
                commission = (revenue * .02m);
            }

            else if (employeeType == "HC")

            {
                totalPay = ((12 * hours) + commission);
                commission = (revenue * .01m);
            }

            else if (employeeType == "HNC")
            {
                totalPay = (16 * hours);
                commission = (revenue * 0);
            }

            txtTotalPay.Focus();
}

如果您认为这会在我的代码中的另一种情况下再次出现,或者如果您发现任何可能有问题的地方,请告诉我。谢谢!

【问题讨论】:

  • @AdrianoRepetti 这个问题将在几秒钟内结束,因为我们在 CR 上不处理损坏的代码。
  • 赫斯拉赫,你是对的。从上一段开始,我认为他已经知道如何解决它

标签: c# windows forms decimal


【解决方案1】:

您应该使用TryParse。发生此错误是因为您的字符串不是有效的十进制。在这种情况下,您可以根据需要显示错误。

decimal commission = 0;

if(!decimal.TryParse(txtSalesCommission.Text, out commission))
{
     //show error to the user and tell him to fill proper decimal value
     return; //exit the method
}

编辑:Decimal.TryParse Method (String, Decimal)msdn 中的文章

【讨论】:

  • TryParse 是做什么的?
  • 尝试将您的字符串解析为有效的十进制数。如果解析成功,您将在先前定义的佣金变量中收到此解析的值。如果不是,commision 的值保持为 0。因此,如果 txtSalesCommission 的文本是“Text123”,这将返回 0 用于我的代码与您的代码,它会抛出一个格式异常。
  • @DerekGroves 这解决了你的问题吗?
  • 确实如此,我对 totalpay 变量做了同样的事情,但是当我运行表单并在 3 个文本框中输入值时,它会在佣金和总薪酬文本框中显示 0.00 美元。
  • @DerekGroves 你在文本框中运行什么值?
【解决方案2】:

另外,我对 tryParse 和异常不太熟悉,所以如果我改为 Parse 并执行 try catch 语句可以吗?因为我这样做了,但是当我在员工类型中输入“S”,在工作时间中输入“30”,在销售收入中输入“200”时,我收到了无效数字格式的失败消息。

这是我的代码:

private void btnCalculate_Click(object sender, EventArgs e)       
{ 
try            
{
            string employeeType = txtEmployeeType.Text;
            decimal hours = Convert.ToDecimal(txtHoursWorked.Text);
            decimal revenue = Convert.ToDecimal(txtSalesRevenue.Text);
            decimal commission = Decimal.Parse(txtSalesCommission.Text);
            decimal totalPay = Decimal.Parse(txtTotalPay.Text);

            txtSalesRevenue.Text = revenue.ToString("c");
            txtSalesCommission.Text = commission.ToString("c");
            txtTotalPay.Text = totalPay.ToString("c");

            //Employee Types: S   = Salaried Employees
            //                HC  = Hourly Commission Employees
            //                HNC = Hourly Non-Commission Employees  

            if (employeeType == "S")

            {
                totalPay = (300 + commission);
                commission = (revenue * .02m);
            }

            else if (employeeType == "HC")

            {
                totalPay = ((12 * hours) + commission);
                commission = (revenue * .01m);
            }

            else if (employeeType == "HNC")
            {
                totalPay = (16 * hours);
                commission = (revenue * 0);
            }
        }

        catch (FormatException)
        {
            MessageBox.Show(
                "Invalid numeric format. Please check all entries.",
                "Entry Error");
        }
        catch (OverflowException)
        {
            MessageBox.Show(
                "Overflow error. Please enter smaller values.",
                "Entry Error");
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                ex.Message,
                ex.GetType().ToString());

            txtTotalPay.Focus();

        }
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多