Reputation: 1627
So I have a form with some tab objects, group objects and possible a table layout pannel inside of a group object.
Based on data locks the form will disable almost all of its content so I need to mark things as read only so the users can still see the data but not change it...
Here is the code I have to dive through collections and mark objects as read only...
private void lockForm()
{
btnLockData.BackColor = Color.LightBlue;
btnLockData.Text = "Data locked! Click to unlock...";
foreach (Control formObject in this.Controls)
{
if (formObject is TabControl)
{
foreach (Control tabControl in (formObject.Controls))
{
foreach (Control tabPageObject in (tabControl.Controls))
{
if (tabPageObject is TextBox)
((TextBox)tabPageObject).ReadOnly = true;
if (tabPageObject is DataGridView)
((DataGridView)tabPageObject).ReadOnly = true;
if (tabPageObject is GroupBox)
{
foreach (Control groupBoxObject in tabPageObject.Controls)
{
if (groupBoxObject is TextBox)
((TextBox)groupBoxObject).ReadOnly = true;
if (groupBoxObject is DataGridView)
((DataGridView)groupBoxObject).ReadOnly = true;
if (groupBoxObject is TableLayoutPanel)
{
foreach (Control layoutObject in groupBoxObject.Controls)
{
if (layoutObject is TextBox)
((TextBox)layoutObject).ReadOnly = true;
if (layoutObject is DataGridView)
((DataGridView)layoutObject).ReadOnly = true;
}
}
}
}
}
}
}
}
dgvResources.ReadOnly = false;
dgvDirectLabor.ReadOnly = false;
}
Is there a better way to control this behavior?
Upvotes: 1
Views: 394
Reputation: 6296
For more granular control of which controls to set Readonly try:
this.Controls.Cast<Control>()
.Where(ctl => ctl is TextBox).Cast<TextBox>().ToList()
.ForEach(e => e.ReadOnly = true);
this.Controls.Cast<Control>()
.Where(ctl => ctl is DataGridView).Cast<DataGridView>().ToList()
.ForEach(e => e.ReadOnly = true);
Upvotes: 2
Reputation: 6515
This should do the trick for WinForms:
var controls = from controls in this.Controls.OfType<Control>()
select controls;
foreach(c in controls) { c.Enabled = false; }
Upvotes: 0