所以我有一个表单,一些选项卡对象,组对象和可能的表布局面板内的组对象。
基于数据锁,表单将禁用几乎所有的内容,所以我需要将内容标记为只读,这样用户仍然可以看到数据,但不能更改它…
下面是我必须深入研究集合并将对象标记为只读的代码…
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;
}
有没有更好的方法来控制这种行为?
要更细粒度地控制要设置只读的控件,请尝试:
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);
这对于WinForms应该是有效的:
var controls = from controls in this.Controls.OfType<Control>()
select controls;
foreach(c in controls) { c.Enabled = false; }