[ Loop through all textbox and dropdown controls on a webform and disable them ]
Having some trouble with this one. I want to loop through every textbox and dropdown control on a webform and disable them under cerrtain conditions. I'm finding a lot of sample code for winforms, but apparently in a webform you can't use Control.Enabled because it doesn't exist. I've got this, which (again) doesn't work because I'm using a webform:
private void DisableControls(Control con)
{
foreach (Control c in con.Controls)
{
DisableControls(c);
}
con.Enabled = false;
}
private void EnableControls(Control con)
{
if (con != null)
{
con.Enabled = true;
EnableControls(con.Parent);
}
}
and I would call them in my Page_Load event like so:
protected void Page_Load(object sender, EventArgs e)
{
// If certain conditions exist, then...
DisableControls(this);
EnableControls(Button1);
}
Answer 1
Why you are using recursion ? I don't understand that part.
You can make your method generic
private void DisableControls<T>(IEnumerable<T> controls) where T: Control
{
foreach(var control in controls)
{
control.Enabled = false;
}
}
Then call it:
DisableControls(this.Controls.OfType<TextBox>());
DisableControls(this.Controls.OfType<ComboBox>());
Answer 2
You could implement a walker:
public void ApplyToAllControls(Control node, Action<Control> lambda)
{
lambda(node);
foreach(Control c in node.Controls)
{
ApplyToAllControls(c, lambda);
}
}
And implement two lambdas like this:
private void ControlDisabler(Control c)
{
if(c != Button1)
{
c.Enabled = false;
}
}
private void ControlEnabler(Control c)
{
if(c != Button1)
{
c.Enabled = true;
}
}
You then invoke them this way:
ApplyToAllControls(root, ControlDisabler);
ApplyToAllControls(root, ControlEnabler);
There are surely some rough edges you can smooth out but you should already get the basic idea.
With currying you can even parameterize the lambdas but that's a bit far to go.
Answer 3
private void DisableControls()
{
var Controls = this.Controls.OfType<TextBox>();
foreach (Control c in Controls)
{
((TextBox)c).Enabled = false;
}
}
private void EnableControls()
{
var Controls = this.Controls.OfType<TextBox>();
foreach (Control c in Controls)
{
((TextBox)c).Enabled = true;
}
}
Answer 4
fastest solution you can use is change the
private void DisableControls(Control con)
to:
private void DisableControls(WebControl con)
that should work, of course do the same in the loop....
and now the explanations, the class Control doesn't have a definition for Enabled it is defined in an upper level base class ( WebControl ), so this is why you need to use it to gain access to enabled .
EDIT:
just checked the code and it fails on the literal control that is new line ( it inherits directly from control )
so the only other thing you need to add is something like this:
foreach (WebControl con in form1.Controls.OfType<WebControl>())
{
con.Enabled = false;
}