错误代码:Decimal price = Decimal.Parse(txtprice.Text);
private void button1_Click(object sender, EventArgs e)
{
decimal height1 = decimal.Parse(txtnorthheight.Text);
decimal length1 = decimal.Parse(txtnorthlength.Text);
decimal area1 = height1 * length1;
lblnortharea.Text = area1.ToString("n");
decimal height2 = decimal.Parse(txtsouthheight.Text);
decimal length2 = decimal.Parse(txtsouthlength.Text);
decimal area2 = height2 * length2;
lblsoutharea.Text = area2.ToString("n");
decimal height3 = decimal.Parse(txteasthheight.Text);
decimal length3 = decimal.Parse(txteasthlength.Text);
decimal area3 = height3 * length3;
lbleastarea.Text = area3.ToString("n");
decimal height4 = decimal.Parse(txtwesthheight.Text);
decimal length4 = decimal.Parse(txtwestlength.Text);
decimal area4 = height4 * length4;
lblwestharea.Text = area4.ToString("n");
decimal height5 = decimal.Parse(txtwinheight.Text);
decimal length5 = decimal.Parse(txtwinlength.Text);
decimal area5 = height5 * length5;
lblwinharea.Text = area5.ToString("n");
decimal areatotal = (area1 + area2 + area3 + area4) - area5;
lbltotalarea.Text = areatotal.ToString("n");
decimal Heightt = (height1 + height2 + height3 + height4) - height5;
decimal Legntht = (length1 + length2 + length3 + length4) - length5;
Height2.Text = Heightt.ToString("n");
Legnth.Text = Legntht.ToString("n");
Decimal price = Decimal.Parse(txtprice.Text);
Decimal undercoat = Decimal.Parse(txtunder.Text);
decimal roomcost = (Heightt * Legntht) * price * undercoat;
txtprice.Text = roomcost.ToString("c");
decimal Vattotal = (25 % roomcost);
lblvat.Text = Vattotal.ToString("c");
Decimal vt = Vattotal + roomcost;
lblbt.Text = vt.ToString("c");
}
工作没有问题,但现在我正在重建程序由于一些错误,这行代码不想工作。有任何想法吗 ?
如果要求,我可以发布整个269行代码以及visual studio错误代码。
答案 0 :(得分:0)
FormatException
,则 Decimal.Parse(string s)
会抛出decimal
。
您可以改为使用Decimal.TryParse(string s, out Decimal d)
。
decimal d = 0;
if(Decimal.TryParse(txtnorthheight.Text, out d))
{
// If the string could be parsed, d contains the value.
// otherwise TryParse returns false.
}
为了使其易于管理,您可能希望将功能分解为更小的部分并首先解析输入。否则,如果整个方法中存在多个点,则由于输入无效而可能必须退出,逻辑会变得混乱。
另一种方法是使用验证来确保只能输入某些类型的值。 Here是有关Windows窗体验证的一些文档。 (我无法确定您是否正在使用Forms或ASP.NET。)