gpt4 book ai didi

c# - 与未命名的文本框关联的 NumericUpDown

转载 作者:行者123 更新时间:2023-11-30 22:11:45 25 4
gpt4 key购买 nike

我一直在尝试调试一个表单大约 15 个小时,终于发现了问题所在。似乎所有 NumericUpDown 控件都有一个关联的未命名的 TextBox 控件。我的问题可以重现如下:

  1. 使用单一表单创建一个新项目
  2. 在窗体上放置一个按钮、一个 TextBox 和一个 NumericUpDown
  3. 在表单中使用如下代码

    private int testing = 0;
    public Form1()
    {
    InitializeComponent();
    }


    private void Form1_Load(object sender, EventArgs e)
    {
    Mytest(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
    NumericUpDown nud;
    foreach (Control c in this.Controls)
    {
    if (c is TextBox)
    {
    c.Text = "that";
    }
    if (c is NumericUpDown)
    {
    nud = c as NumericUpDown;
    nud.Value = 0;
    }

    }
    }
    private void TestEmpty(Control ctl)
    {
    foreach (Control c in ctl.Controls)
    {
    if (c is TextBox && c.Name == "")
    {
    ++testing;
    c.BackColor = Color.Red;
    c.Text = "Something";
    }
    TestEmpty(c);
    }
    }
    private void Mytest(Control ctl)
    {
    TestEmpty(this);

    MessageBox.Show("Found " + testing.ToString() + " items");
    }
  4. 将表单的加载事件和按钮的点击事件分配给代码中的处理程序

  5. 运行表单

最初,NumericUpDown 控件包含文本“Something”。如果单击该按钮,则不会分配新值 0。

但是,如果您在按钮的单击事件中为 NumericUpDown Value 属性分配了一个非零值:

nud.Value = 42;

按钮按预期工作。

将任何文本分配给与 NumericUpdown 控件关联的未命名文本框后,就不可能将零值分配给 NumericUpDown。

我在很多地方使用这样的递归代码来填充和重置表单。现在我知道问题出在哪里,我可以通过检查未命名的 TextBox 来解决它:

if (c is TextBox && c.Name != "")

但这看起来非常丑陋并且可能容易出错。

我是不是误会了什么?在循环控件时,是否有更简洁的方法来处理这些虚假的文本框?

最佳答案

After any text has been assigned to the unnamed Text Box associated with the NumericUpdown control, it is not possible to assign a value of zero to the NumericUpDown.

这不太对。

发生的情况是 NumericUpDown 的 Value 当前为零(因为这是您将它放在 Form 上时的初始值),但 Text 属性显示为其他。但是,在下面,值仍然为零。

当您尝试“重置”NumericUpDown 时,您将其分配为零...但值已经为零(在引擎盖下),因此它不会自行刷新(为什么会这样?...在​​正常操作下不可能在其中显示非数字文本)。如果您先将值更改为 Maximum(),然后再更改回 Minimum(),则这一点很明显:

                nud = c as NumericUpDown;
nud.Value = nud.Maximum;
nud.Value = nud.Minimum;

假设最小值和最大值不是同一个数字,这将强制 NumericUpDown 刷新自身并显示零。

现在,如果控件是 TextBox 或 NumericUpdown,您可以通过简单地不递归到控件中来防止此问题,这些控件是您有兴趣重置的控件。一个简单的重写:

    private void Reset(Control ctl)
{
foreach (Control c in ctl.Controls)
{
if (c is TextBox)
{
c.Text = "";
}
else if (c is NumericUpDown)
{
NumericUpDown nud = c as NumericUpDown;
nud.Value = nud.Minimum;
}
else if (c.HasChildren)
{
Reset(c);
}
}
}

关于c# - 与未命名的文本框关联的 NumericUpDown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com