Disabling Form Objects

  • Thread starter Thread starter dm1608
  • Start date Start date
D

dm1608

I have to issues:

1) Does anyone know of a programmatic way I can disable all textboxes,
combo, listboxes, and buttons on a form?

2) What is the best practice for disabling multiple controls on a form.
Basically, I need to disable almost everything on a form and re-enable when
a particular task is complete. It seems like I duplicate the code over and
over in the code... then later when I add a new control, I invariably miss
something.....
 
Two possibilities:

1. Write code that goes through all of the controls on a form
(recursively walking through the Control list, disabling controls).
This has the advantage that you can pass in controls that you don't
want disabled, and selectively avoid them:

public static void DisableAllControlsExcept(Form myForm, params
Control[] exceptions) ...

2. I've noticed that if you disable a container, such as a Panel, it
disables all controls inside the container, although I don't have time
to try it out right now. The only downside is that you can't make any
exceptions.
 
By the way, you could write that static method like this (untested code
follows):

public static ArrayList DisableAllControls(ContainerControl container,
params Control[] exceptions)
{
ArrayList disabledControls = new ArrayList();
foreach (Control c in container)
{
ContainerControl childContainer = c as ContainerControl;
if (childContainer != null)
{

disabledControls.AddRange(DisableAllControls(childContainer,
exceptions));
}
else if (Array.IndexOf(exceptions, c) < 0 && c.Enabled)
{
c.Enabled = false;
disabledControls.Add(c);
}
}
return disabledControls;
}

then when you want to enable them again, you can just do:

foreach (Control c in disabledControls)
{
c.Enabled = true;
}

and any that were disabled before the original call to
DisableAllControls are left disabled.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top