Reputation: 536
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?
Upvotes: 0
Views: 169
Reputation: 39122
More code golf (it's technically one line): Assumes the TextBoxes are directly contained by the Form
public Form1()
{
InitializeComponent();
checkBox1.Checked = true;
checkBox1.CheckedChanged += (sender, e) => { foreach (TextBox tb in this.Controls.OfType<TextBox>()) { tb.Enabled = ((CheckBox)sender).Checked; } };
}
Upvotes: 0
Reputation: 18843
var cntrlCollections = GetAll(this,typeof(TextBox));
foreach (Control ctrl in cntrlCollections)
{
ctrl.Enabled = checkBox.Checked;
}
Upvotes: 0
Reputation: 149010
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);
or
new [] { textBox1 ... }.AsParallel().ForAll(tb => tb.Enabled = true);
Upvotes: 0
Reputation: 6490
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
Upvotes: 1
Reputation: 6698
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.
Upvotes: 0