views:

149

answers:

3

How can I enable/disable an asp.net form/controls selectively or entirely from code-behind?

The following code is not working. Coz there is no Enabled property in this case.

public static void Disable(Page container)
{
    for (int i = 0; i < container.Controls.Count; i++)
    {
        container.Form.Controls[i].Enabled = false;
    }
}
+2  A: 

Only the controls that inherit from WebControl will have a Enabled property. So you could do something like this inside your loop:

var webControl = container.Form.Controls[i] as WebControl;
if(webControl != null) {
    webControl.Enabled=false;
}
Konamiman
Documentation says Enabled false will "dim" the controls and make them not editable at the client side. It's closer to what JMSA wants but documentation says it's only functional in browsers compatible with "Internet Explorer 4+". WTF is a browser compatible with IE4?
Ciwee
It doesn't seem to be browser safe though
Ciwee
A: 

You may use Visible instead of Enabled. ASP.NET framework will not call the Render method of controls which Visible property is set to false.

From the documentation:

If this property is false, the server control is not rendered. You should take this into account when organizing the lay out of your page.

Ciwee
A: 

Are you casting the controls as your are pulling them out? Your sample code seems to indicate that you're not, which would of course result in no Enabled property. Although I don't know what controls you are pulling out, chances are they will have an Enabled property if you cast them to their proper types.

Paul McLean
I don't believe the code he code he showed here really works.. Form.Controls is of type ControlCollection which is a Control list hence not exposing the Enabled property
Ciwee