C# 与未命名文本框关联的NumericUpDown
我试着调试一个表单大约15个小时,终于发现了问题所在。似乎所有NumericUpDown控件都有一个未命名的关联文本框控件。我的问题可以复制如下:C# 与未命名文本框关联的NumericUpDown,c#,numericupdown,C#,Numericupdown,我试着调试一个表单大约15个小时,终于发现了问题所在。似乎所有NumericUpDown控件都有一个未命名的关联文本框控件。我的问题可以复制如下: 使用单个表单创建新项目 在表单上放置一个按钮、一个文本框和一个数字UpDown 在表单中使用以下代码 private int testing = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e)
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");
}
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");
}
最初,NumericUpDown控件包含文本“Something”。如果单击该按钮,则不会指定新值0
但是,如果在按钮的单击事件中将nnon零值指定给NumericUpDown value属性:
nud.Value = 42;
按钮按预期工作
将任何文本指定给与NumericUpdown控件关联的未命名文本框后,无法将零值指定给NumericUpdown
我在许多地方使用类似这样的递归代码来填充和重置表单。现在我知道了问题所在,我可以通过检查一个未命名的文本框来解决它:
if (c is TextBox && c.Name != "")
但这看起来非常丑陋,而且可能容易出错
我误解了什么吗?在控件之间循环时,是否有更干净的方法来处理这些虚假的文本框
将任何文本指定给关联的未命名文本框后
使用NumericUpdown控件,无法指定值
从零到数字向上向下
那不太对
发生的情况是NumericUpDown的值当前为零(因为这是您将其放到表单上时的初始值),但Text属性显示为其他值。但在下面,该值仍然为零
当您尝试“重置”数值UpDown时,您为其指定了零…但该值已经为零(在引擎盖下方),因此它不会刷新自身(为什么会刷新?。在正常操作下,不可能在其中显示非数值文本)。如果先将值更改为最大值(),然后再将其更改为最小值(),这一点很明显:
假设最小值和最大值不是同一个数字,这将强制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);
}
}
}
我已经编辑了你的标题。请看“”,其中的共识是“不,他们不应该”。你能用纯文本解释一下你想要实现什么吗?@rapsalands上面的代码刚刚演示了这个问题。在实际应用程序中,我通过在控件中循环并将文本框设置为“”和NumericUpDowns设置为其最小值(通常为零)来重置表单。我不能这样做,因为将所有文本框设置为“”会阻止我将NumericUpDowns设置为零。这就是原因。谢谢事实上,它比这复杂一点,因为我在选项卡和面板中处理大约70个不同类型的控件(组合、屏蔽文本框以及文本框和数字上下),所以我需要递归,但你给了我我所需要的支持。