0

I created a windows form with several buttons, text boxes, combo boxes, etc. At some point during execution, I disable all of them as follows:

Control01.Enabled = false; Control02.Enabled = false; Control03.Enabled = false; // ... Control10.Enabled = false; 

How can I automate this?

3 Answers 3

5

You can enumerate controls and disable them:

foreach(var control in Controls.Cast<Control>()) control.Enabled = false; 

If you want to disable only buttons, you can use LINQ

foreach(var control in Controls.OfType<Button>()) control.Enabled = false; 

Or if you have some other criteria of selection

var controlsToDisable = Controls.OfType<TextBox>() .Where(t => t.Name.StartsWith("Control")); // etc foreach(var control in controlsToDisable) control.Enabled = false; 
Sign up to request clarification or add additional context in comments.

5 Comments

but note: foreach (Button b in Controls) is not equal to the LINQ Expression. (This is often seen, but it would result in trying to cast EVERY control to a "Button")
@dognose nope, there is method Cast<Button> which will try to cast all controls to button. OfType<Button> will return only those control which can be cast to button
And it might help to put those controls in an array if they're spread across the user-interface (e.g. not being inside single container, or are but with other controls that shouldn't be disabled).
For some reason, it is not recognizing the Enabled method. :-( oi44.tinypic.com/vdif0l.jpg
@JosuéMolina sorry, you need to cast to control type Cast<Control>() because by default enumerator will return objects. Fixed!
1

You could use a for loop combined with the Controls.Find() method :

string controlIdNr =""; for(int i=1;i++;i<11) { controlIdNr = "Control" + i.ToString().PadLeft(2,'0'); this.Controls.Find(controlIdNr,true).Enabled = false; } 

This is of course if your controls have a structured id value. If you want to disable all controls, or all controls of a given type, lazyberezovsky's answer is better !

P.S : I haven't tested code, but that's the idea anyway...

1 Comment

@lazyberezovsky > indeed ! I editted my answer. I'm more a ASP.NET guy and FindControl() only requires the control's id ;-)
1

If your layout allows it, you can put them on a panel and disable the panel in one line. Or maybe several few panels.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.