How can I create an Array of Controls in C#.NET?

2020-02-29 11:26发布

问题:

I have a form which contains several standard controls (textbox's, buttons, etc). I want to group certain controls in collections so that I can enable and disable them at any given time without having to explicitly set each one. What is the syntax to do that? Here is some pseudo code to show what I want to do....

Control[] ControlCollection = new Control[];
ControlCollection.add(Button1);
ControlCollection.add(TextBox1);
...
...
foreach( Control x in ControlCollection)
{
    x.Enabled = false;
}

I know I could put the controls in say a group box and accomplish this but the controls are not positioned on the form in such a manner that it is convenient to do so.

回答1:

your example should be fine

List<Control>

will also work



回答2:

Have you considered using a layout manager? (as far as positioning goes) Keeping a list of controls (without specifying the control's position) will not automatically position the controls, a layout manager could help.



回答3:

If your not already using the tag property of the control then you could put some form of controlid in the tag and then enumerate the controls collection looking for the particular id you want and enable/disable them.



回答4:

Assuming you are using webforms and .net 3.5 you could have something like

var cntrls = new List<WebControl>()
        {
            {new TextBox(){ID = "Textbox1"}},
            {new Button(){ID="Button1", Text = "Click me!"}}
        };

cntrls.ForEach(x => x.Enabled = false);