private void HideAll() { foreach (TextBox tb in this.Controls.OfType<TextBox>()) tb.Enabled = false; } 

I have four TextBox and one ComboBox . Depending on the selected item in the ComboBox , you need to enable / disable (Enabled) the TextBox .

The most, as I thought, the best option is to first turn everything off and then turn on the necessary ones, but for some reason the function is not called at all, even inserted a MessageBox - all is in vain.

Tell me, please, what is the matter or another optimal variant, because in my variant I did not take into account that all TextBox will be hidden on the form (I actually have not four, but more)

 comboBox1.SelectedIndexChanged += (s, e) => { comboBox2.Items.Clear(); if (comboBox1.SelectedIndex == 0) { HideAll(); textBoxAn1.Enabled = true; textBoxAn2.Enabled = true; } else if (comboBox1.SelectedIndex == 1) { HideAll(); textBoxAn1.Enabled = true; textBoxAn2.Enabled = true; textBoxAn3.Enabled = true; } else if (comboBox1.SelectedIndex == 2) { HideAll(); textBoxAn1.Enabled = true; textBoxAn2.Enabled = true; textBoxAn3.Enabled = true; textBoxAn4.Enabled = true; } comboBox2.SelectedIndex = 0; }; 
  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

1 answer 1

The Controls property for a control returns only those elements that are directly in it. To bypass all items (including nested), use the recursive option:

  public static IEnumerable<Control> GetAll(this Control control) { var controls = control.Controls.Cast<Control>(); return controls.SelectMany(ctrl => GetAll(ctrl)).Concat(controls); } 

In your case, this is not necessary, because simply select the grouping element for iteration:

 foreach (TextBox tb in groupBox1.Controls.OfType<TextBox>())