首页 > 解决方案 > 使用 numericUpDown 的 ReadOnly false 处理用户编号输入值条件

问题描述

在 C# WinForms 桌面应用程序中,我使用 2 个相互依赖numericUpDown1 minnumericUpDown2 maxnumericUpDown控件:

private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
{
    if (numericUpDown1.Value <= numericUpDown2.Value)
    {
        min = (int)numericUpDown1.Value;
    } 
    else
    {
        numericUpDown1.Value = min - 1;
    }
}

private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
    if (numericUpDown2.Value >= numericUpDown1.Value)
    {
        max = (int)numericUpDown2.Value;
    }
    else
    {
        numericUpDown2.Value = max + 1;
    }
} 

使用 ofReadOnly = true;来避免手动输入的最大值小于最小值numericUpDown

        min = 20;
        max = 1999;

        numericUpDown1.Value = min;
        numericUpDown2.Value = max;

        numericUpDown1.ReadOnly = true;
        numericUpDown2.ReadOnly = true;

        numericUpDown1.Increment = 1;
        numericUpDown2.Increment = 1;

        numericUpDown1.Maximum = 2000;
        numericUpDown1.Minimum = 1;
        numericUpDown2.Maximum = 2000;
        numericUpDown2.Minimum = 1;

但我使用的范围很大,从 1 到 2000,并且希望允许用户numericUpDown使用ReadOnly = false;.

我试图弄清楚,如何使用 of 来控制用户输入条件ReadOnly = false;numericUpDown以避免输入的最大数字小于最小或最小大于最大。

标签: c#event-handlingreadonlynumericupdown

解决方案


试试这个解决方案:

首先设置您的 numericUpDown 属性 ReadOnly=false 或在您的 FormLoad_Function 中编写一行代码,

numericUpDown1.ReadOnly = false;
numericUpDown2.ReadOnly = false;

然后

private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
{
    if (numericUpDown1.Value > numericUpDown2.Value)
    {
        numericUpDown1.Value = numericUpDown1.Value - 1;
        MessageBox.Show("Min value always less then Max value");
    } 
}

private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
    if (numericUpDown1.Value > numericUpDown2.Value)
    {
        numericUpDown2.Value = numericUpDown2.Value + 1;
        MessageBox.Show("Max value always greater then Min value");
    } 
} 

推荐阅读