0

I want to disable some controls on my asp page from a ControlCollection.

This is my code.

foreach (System.Web.UI.Control c in ControlCollection)
{
   if (c.GetType().FullName.Equals("System.Web.UI.WebControls.Table"))
   {
        TableRow t = (TableRow)c;
        t.Enabled = false;
   }
   else if (c.GetType().FullName.Equals("System.Web.UI.WebControls.TextBox"))
   {
        TextBox t = (TextBox)c;
        t.Enabled = false;
   }
  .......
  ......
  ///Like this I do for all controls
}

I need a better approach at this. I searched on Internet but didn't find any solution.

3 Answers 3

1

You can use the .OfType<> extension like this in order to have more elegant code:

collection.OfType<Table>().ToList().ForEach(c => c.Enabled = false);
collection.OfType<TextBox>().ToList().ForEach(c => c.Enabled = false)
Sign up to request clarification or add additional context in comments.

Comments

0

Do all controls in your list inherit from System.Web.UI.WebControl? If so, than this code may help. (Didn't test it myself)

Type wc = new System.Web.UI.WebControls.WebControl(HtmlTextWriterTag.A).GetType();

    foreach (System.Web.UI.Control c in ControlCollection)
    {
        if (c.GetType().IsSubclassOf(wc))
        {
            ((System.Web.UI.WebControls.WebControl)c).Enabled = false;
        }
    }

And even more elegant (thanx to Shadow Wizard )

ControlCollection.OfType<System.Web.UI.WebControls.WebControl>().ToList().ForEach(c => c.Enabled = false);

3 Comments

Yes this is what i want to do. All my controls are web controls. But I get these errors for which I need your help. If I write Type wc = GetType(new System.UI.WebControl()); I get error saying UI does not exist in System. If I write Type wc = new System.Web.UI.WebControls.WebControl().GetType(); It says WebControl is inaccessible due to its protection level.
I have edited my code. This code works. One reminder: the controlcollection of a page does only contain the first level of controls. Controls such as a panel will have their own set of childcontrols.
Thanks..This saved me lots of coding and I got to learn something new. :)
0

Try to use is.

if (c is Table)
{

}
else if (c is TextBox)
{

}

Or consider doing a switch statement on the type name.

switch (c.GetType().Name.ToLower())
{
  case "table":
    break;
  case "textbox":
    break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.