-1

I am getting this error: Unable to cast object of type ‘System.Web.UI.LiteralControl’ to type ‘System.Web.Controls.TextBox

foreach(Control x in this.Controls)
{
 Button btn = (Button)x;
 btn.Enabled = true;
}
Naseef K
  • 1
  • 1

1 Answers1

1

Some of your controls are not buttons. If you try to cast them to a button you will get this error.

You can remove non-buttons from the list with a bit of LINQ and the OfType() method. Using OfType() will also automatically cast the result so you don't need the intermediate variable.

//using System.Linq;
foreach(Button btn in this.Controls.OfType<Button>())
{
    btn.Enabled = true;
}

If you want to do it the old-fashioned way here it is:

foreach(Control x in this.Controls)
{
    Button btn = x as Button;
    if (btn != null)
    {
        btn.Enabled = true;
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80