Enabling many textBoxes at the same time

I have 10 textBoxes in one form and I have a checkBox.

I would like this checkBox to control if the textBoxes are enabled or not. I know I can do it textBox1.Enabled = true; textBox2.Enabled = true; etc but is there any way to do it in one line or shorter?


You can do this in one line of Code as follows,

You place all the text boxes inside a group box or a panel.

Pnl.Enabled = Chk.Checked

private void ToggleAllTextBoxControls()
    foreach (Control c in this.Controls)
        if (c Is TextBox)
             c.Enabled = chkEnable.Checked;

This will iterate through all controls on the form and enable it if it's a TextBox and the checkbox is checked.

The cleanest way is to create an array of TextBox's first, and then iterate over it.

var textBoxes = new TextBox[] { ... };


foreach(var tb in textBoxes)
    tb.Enabled = true;

But you asked for a solution "in one line or shorter". To do it in one line, you'd have to do this:

new [] { textBox1 ... }.ToList().ForEach(tb => tb.Enabled = true);


new [] { textBox1 ... }.AsParallel().ForAll(tb => tb.Enabled = true);

var cntrlCollections = GetAll(this,typeof(TextBox));

foreach (Control ctrl in cntrlCollections)
  ctrl.Enabled = checkBox.Checked;

More code golf (it's technically one line): Assumes the TextBoxes are directly contained by the Form

    public Form1()
        checkBox1.Checked = true;
        checkBox1.CheckedChanged += (sender, e) => { foreach (TextBox tb in this.Controls.OfType<TextBox>()) { tb.Enabled = ((CheckBox)sender).Checked; } };

Need Your Help

Binding ColumnDefinition.Width to a DataGridTextColumn does not fire when the usercontrol loads

binding datagrid wpf-controls datagridtextcolumn

I have a WPF usercontrol that holds a grid, some textboxes, and a DataGrid. The textboxes are filers for the data in each column so I'd like them to stay above the relevant column. This is easy unl...

How Create Post Request with redirect like a Form Submit

ruby-on-rails ruby forms

How can in controller redirect with post same data like this do form

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.