使用Convert.ToDecimal进行格式异常

时间:2016-10-19 21:00:43

标签: c# exception format try-catch

我一直收到我自己的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();
    }
   }
}

0 个答案:

没有答案
相关问题