如何使用NumericUpDown计算文本框值的总数?

İlk*_*kut 2 c# textbox numericupdown

我正在尝试制作一个小的披萨订单,但我的计算有问题.选择披萨后,单价和总计算都可以,但选择添加会引入问题.更改NumericUpDown值后,卡路里不正确(所有单位都有不变的价格和卡路里).NumericUpDown的名称是numberofunit.我该怎么计算它们?

if (pepper.Checked)
{
    string peppereklendi = 
        Convert.ToString(Convert.ToDouble(unitprice.Text)+ pepperprice);

    unitprice.Text = peppereklendi;

    total.Text = 
        Convert.ToString(Convert.ToDecimal(unitprice.Text) * numberofunit.Value);

    string pepperkaloriekle = 
        Convert.ToString(Convert.ToInt16(gizlikalori.Text) + pepperkalori);

    gizlikalori.Text = pepperkaloriekle;

    amountofcalorie.Text = 
        Convert.ToString(Convert.ToDecimal(gizlikalori.Text) * numberofunit.Value);
}
else
{
    string peppereklendi = unitprice.Text;

    unitprice.Text = 
        Convert.ToString(Convert.ToDouble(peppereklendi) - pepperprice);

    total.Text = Convert.ToString(Convert.ToDecimal(unitprice.Text) * numberofunit.Value);

    string pepperkaloriekle = gizlikalori.Text;

    gizlikalori.Text = 
        Convert.ToString(Convert.ToDouble(pepperkaloriekle) - pepperkalori);

    amountofcalorie.Text = 
        Convert.ToString(Convert.ToDecimal(gizlikalori.Text) * numberofunit.Value);
}
Run Code Online (Sandbox Code Playgroud)

此代码是胡椒的复选框代码.

这是我的申请表.

Oli*_*bes 6

您应该尝试将计算逻辑与UI逻辑(表单)分开.然后事情会变得更加清晰:

// Get values from the text boxes
decimal up = Convert.ToDecimal(unitprice.Text);
decimal calories = Convert.ToDecimal(gizlikalori.Text);
decimal tot, totCalories;

// Do the calculation
if (pepper.Checked) {
    up = up + pepperprice;
    calories = calories + pepperkalori;
}
tot = up * numberofunit.Value;
totCalories = calories * numberofunit.Value;

// Assign the results to text boxes
unitprice.Text = up.ToString();
total.Text = tot.ToString();
gizlikalori.Text = calories.ToString();
amountofcalorie.Text = totCalories.ToString();
Run Code Online (Sandbox Code Playgroud)

你做错了,是你从单价和单位卡路里中减去辣椒价格和辣椒卡路里,如果没有选择辣椒.然而,单价(和卡路里)已经没有胡椒了!

我不知道你什么时候进行这个计算,但是如果你每次增加单位数时都执行它,那么你每次都要加胡椒价!当您检查添加时,基本单价的单独变量可能会更好.然后始终从基本单价开始计算.

此外,您正在混合许多不同的数字类型.这毫无意义.

增强代码的下一步是为计算创建一个单独的类.您还可以使用数据绑定.这将完全消除进行转换的需要.请参阅我对以下帖子的回答:manipulating-textbox-variables-in-computation