首页 > 解决方案 > 将 numericUpdown 中的值与文本框上的值分开并显示在第三个文本框上时出现问题

问题描述

您好,我对这个网站和 C# 非常陌生,我正在尝试在 VS 2017 上构建一个 Winforms 应用程序,其中包含一个 numericUpDown 和 2 个文本框。我需要将文本框 1 中的值除以 numericUpDown 控件上的值,然后在文本框 2 中汇总并显示结果,但以双精度形式显示。我遇到的问题是,在我将 numericupdown 的值向上更改 3 次然后汇总结果错误之前,什么都不会计算。它因 1 值变化而关闭。因此,如果我单击 nud 3 次并且文本框 1 上的值为 0.28,它应该给我一个 0.09333333 的结果,即 0.28 除以 3,但它给了我 0.14。如果我单击 nud,它看起来像是被零除。numericupdown 从 0 值开始的事实与我的问题有什么关系吗?运行应用程序时,我没有收到任何错误消息或异常。我会很感激任何帮助。请不要对我太苛刻,我是 C# 的超级新手,谢谢

这是代码

    private void numericUpDown1R2Scrap_ValueChanged(object sender, EventArgs e)
    {

        double val1 = 0.0;
        double val2 = 0.0;
        double total = 0.0;

        if (!string.IsNullOrEmpty(textBox1WeightSummary.Text) && 
        !string.IsNullOrEmpty(numericUpDown1R2Scrap.Text))
        {


            val1 = double.Parse(numericUpDown1R2Scrap.Text);
            val2 = double.Parse(textBox1WeightSummary.Text);

            if (val1 != 0)
            {
                total = val2 / val1;
                textBox1RingWeightTotal.Text = total.ToString(); 
            }

标签: c#winforms

解决方案


在表单设计器中,将 NumericUpDownMinimumValue属性设置为 1。这允许从 1 开始,并且不允许向下到0.

然后,始终检查NumericUpDown.Value以读取当前值,这是一种decimal类型。

使用Decimal.TryParse转换 TextBox 的数字输入。请注意,默认实现假定您使用当前的文化小数分隔符。如果需要,请参阅有关使用InvariantCulture引用强制使用点作为小数分隔符和逗号作为千位分隔符的文档。

private void numericUpDown1R2Scrap_ValueChanged(object sender, EventArgs e)
{
    NumericUpDown nUpDown = sender as NumericUpDown;
    if (nUpDown.Value == 0) nUpDown.Value = 1;
    if (decimal.TryParse(textBox1WeightSummary.Text, out decimal inputValue)) {
        textBox1RingWeightTotal.Text = (inputValue / nUpDown.Value).ToString();
    }
}

这一行:if (nUpDown.Value == 0) nUpDown.Value = 1;是故障安全的,以防忘记在设计器(或表单的构造函数)中 设置 NumericUpDownValueMinimumto 。1

此行:NumericUpDown nUpDown = sender as NumericUpDown;, 用于检索引发事件的 NumericUpdown 控件的实例。这允许将代码重用于任何其他 NumericUpDown 控件,而无需手动更改引用。

此语法:decimal.TryParse([Some string], out decimal inputValue)需要C# 7.0+.
如果您使用的是该语言的早期版本,则需要在方法之外声明局部变量:

decimal inputValue = 0m;
if (decimal.TryParse(textBox1WeightSummary.Text, out inputValue)) { ... }

在这一行:(inputValue / nUpDown.Value).ToString();中,您可以更改 ToString() 格式,指定要使用的小数位数。例如:

(inputValue / nUpDown.Value).ToString("N2");

将输出一个十进制数,格式为仅显示前 2 个小数位。


推荐阅读