Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

Setting them Enabled / Disabled is easy, see GWLIosa'a answer.

However not all controls have a Read-only property. You could use something like:

foreach (Control c in this.Controls)
{
  if (c is TextBox)
    (c as TextBox).Readonly = newValue;
  else if (c is ListBox)
    (c as ListBox).Readonly = newValue;
  // etc
}

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).

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);
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top