views:

376

answers:

3

I want to be able to set a bunch of controls on a Form to Read-Only and back with a button click. Is there a way to loop through them? this.Controls maybe......

Thanks!

+4  A: 

If you want to set ALL the controls to read only, you can do something like:

foreach(Control currentControl in this.Controls)
{
    currentControl.Enabled = false;
}

If what you really want to do is set SOME of the controls to read only, I'd suggest keeping a list of the relevant controls, and then doing a ForEach on THAT list, rather than all of them.

GWLlosa
+2  A: 

Personally I'd put all the controls (and sub-controls) I want to impact into a Panel - then just change the state of the single Panel. This means you don't have to start storing the old values (to put them back - you might not want to assume they all started enabled, for example).

Marc Gravell
A: 

I'd suggest you use the Enabled property suggested by GWLlosa, but if you want or need to use the ReadOnly Property, try this:

        foreach (Control ctrl in this.Controls)
        {
            Type t = ctrl.GetType();

            PropertyInfo propInfo = t.GetProperty("ReadOnly");

            if (propInfo != null)
                propInfo.SetValue(ctrl, true, null);
        }
Chris Persichetti