Reputation: 8357
I am coding a C# Forms application and would like to know how to enable/disable all controls container within a panel.
Here is my code:
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (var item in panel.Controls)
{
item.enabled = enabled;
}
}
There is no enabled property in the panel.Controls collection.
How can I enable/disable all controls container within a panel.
Thanks in advance.
Upvotes: 8
Views: 37718
Reputation: 14604
You are getting controls as var
and iterating on them and var doesn't contain any property Enabled
. You need to loop through controls and get every control as Control
. Try this
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (Control ctrl in panel.Controls)
{
ctrl.Enabled = enabled;
}
}
Enabled can be true
or false
.
Upvotes: 17
Reputation: 1
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control item in panel.Controls)
if (ctrl is Button)
((Button)item).Enabled = false;
}
Upvotes: -1
Reputation: 5
@anshu
if your controls are HTML controls then use
foreach (Control ctrl in myControl1.Controls)
if (ctrl is HtmlControl)
((HtmlControl)ctrl).Disabled = true;
Upvotes: -1
Reputation: 1411
"How can I enable/disable all controls container within a panel."
A: If you want to disable or enable all controls within a panel, you can directly call,
Panel panel;
-> panel.Enabled = true;//For enabling all controls inside the panel.
-> panel.Enabled = false;//For disabling all controls inside the panel.
If you want only specific controls inside the panel to be enabled or disabled then you can iterate through the collection of controls and set it's enable state to true or false based on your requirement.
Upvotes: 5
Reputation: 203
Try the following code,
private void DisableAll_Click(object sender, EventArgs e)
{
EnabledPanelContents(this.panel1, false);
}
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (Control item in panel.Controls)
{
item.Enabled= enabled;
}
}
Upvotes: 1
Reputation: 210
If you declare item as var (in the foreach loop), it won't have the properties of a windows control. You should declare it as a control.
Try this code snippet and it should work:
foreach (Control item in panel.Controls)
{
item.Enabled = true; // = true: enable all, = false: disable all
}
Upvotes: 1