I have been trying to debug a form for about 15 hours and have finally discovered what the problem is. It appears that all NumericUpDown controls have an associated TextBox control which is unnamed. My problem can be reproduced as follows:
- Create a new project with a single form
- Put a button, a TextBox and a NumericUpDown on the form
Use the following code in the form
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"); }
Assign the form's load event and the button's click event to the handlers in the code
Run the form
Initially, the NumericUpDown control contains the text "Something". If you click the button, the new value of 0 is not assigned.
If, however, you assign a nnon-zero value to the NumericUpDown Value property in the button's click event:
nud.Value = 42;
the button works as expected.
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.
I am using recursive code like this in a number of places to populate and reset forms. Now that I know where the problem lies, I can work around it by checking for an unnamed TextBox:
if (c is TextBox && c.Name != "")
but this seems very ugly and potentially error-prone.
Have I misunderstood something? Is there a cleaner way to handle these spuriously TextBoxes when looping through controls?