我收到此错误"异常详细信息:System.FormatException:输入字符串的格式不正确。"看来我的Convert和Parse没有用。我使用ASP.NET C#。还有一种方法可以只读取数字值而不是使用文本框吗?
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="Payroll" runat="server">
<div>
<h1>Exception Painting</h1>
<h2>Payroll Calculator</h2>
<p>Employee Name: <asp:TextBox ID="Name" runat="server"></asp:TextBox>
<p>Pay Rate: <asp:TextBox ID="PayRate" runat="server"></asp:TextBox>
<p>Salary Employee: <asp:TextBox ID="SalaryEmployee" runat="server"></asp:TextBox>
<p>Hours Worked: <asp:TextBox ID="HoursWorked" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
<%
double overtimeHours = 0;
double overtimePay = 0;
double regularPay = 0;
double totalPay = 0;
double regularHours = 0;
double basePay = 0;
double hrsWrked = 0;
double payRt = 0;
string nm = Name.Text;
hrsWrked = Convert.ToDouble(HoursWorked.Text);
//I cant figure out what im doing wrong here..
hrsWrked = double.Parse(HoursWorked.Text);
string slry = Name.Text;
payRt = Convert.ToDouble(PayRate.Text);
payRt = double.Parse(PayRate.Text);
double overtimePayRt = payRt * 1.5;
if (Page.IsPostBack)
{
Payroll.Visible = false;
if (SalaryEmployee.Equals("no") && hrsWrked > 40)
overtimeHours = hrsWrked - 40;
regularHours = hrsWrked - overtimeHours;
overtimePay = overtimeHours * overtimePayRt;
regularPay = payRt * regularHours;
totalPay = overtimePay + regularPay;
basePay = hrsWrked * 52 * totalPay;
Response.Write("Employee Name: " + nm + "Base Salary: " + basePay + "Hours Worked: " + hrsWrked + "Total Weekly Pay: " + totalPay);
if (SalaryEmployee.Equals("yes"))
regularHours = 40;
totalPay = payRt * regularHours;
basePay = hrsWrked * 52 * totalPay;
Response.Write("Employee Name: " + nm + "Base Salary: " + basePay + "Hours Worked: " + hrsWrked + "Total Weekly Pay: " + totalPay);
}
%>
</body>
</html>
答案 0 :(得分:1)
您正在解析和转换未初始化的值
<p>Employee Name: <asp:TextBox ID="Name" runat="server"></asp:TextBox>
<p>Pay Rate: <asp:TextBox ID="PayRate" runat="server">0.0</asp:TextBox>
<p>Salary Employee: <asp:TextBox ID="SalaryEmployee" runat="server">0.0</asp:TextBox>
<p>Hours Worked: <asp:TextBox ID="HoursWorked" runat="server">0.0</asp:TextBox>
这将使您的代码能够编译,但是每次用户更改它们时都需要检查这些值,因为只要您的值无法解析或正确转换,它就会中断
这是一个捕获错误的方法示例。
bool bueno = true;//spanish for good
try
{
payRt = Convert.ToDouble(PayRate.Text);
payRt = double.Parse(PayRate.Text);
//I cant figure out what im doing wrong here..
hrsWrked = double.Parse(HoursWorked.Text);
}
catch (System.FormatException fEX)
{
bueno = false;
Response.Write(fEX.Message);//you could do more here
}
catch (System.OverflowException ofEX)
{
bueno = false;
Response.Write(ofEX.Message);//you could do more here
}
catch (System.ArgumentException aEX)
{
bueno = false;
Response.Write(aEX.Message);//you could do more here
}
//I would do more about these errors but this is an example
if(bueno)
{
double overtimePayRt = payRt * 1.5;
if (Page.IsPostBack)
{