1 Attachment(s)
how to iterate over controls in page to set properties
using: asp.net 2.0 - [vs2005]
I have a page with a master template named "MasterPage.master" and want to iterate over all of the controls in the Page to set a property.
I tried using this in the Page Unload event:
VB Code:
Dim ctlControl As System.Web.UI.WebControls.WebControl
For Each ctlControl In Page.Controls
ctlControl.Enabled = False
Next
but this gives an exception:
Unable to cast object of type 'ASP.masterpage_master' to type 'System.Web.UI.WebControls.WebControl'.
I tried removing the Master template
but I still get same error but instead of 'ASP.masterpage_master' it
refers to Literal Control.
Am I missing something here?
Please help. Thanks in advance.
Re: how to iterate over controls in page to set properties
Page.Controls returns a ControlCollection - Page is extends TemplateControl which in turn extends Control, whereas your for...each uses an object of WebControl. As for the exception, it details the casting problem - it can't cast from LiteralControl (extends Control) to WebControl.
The safest way to handle a loop of this sort is to use an object of type "System.Web.UI.Control" for your For Each loop, i.e.:
Code:
Dim myControl As Control
For Each myControl in Page.Controls
Re: how to iterate over controls in page to set properties
But I get the same error when I use the sample code that you show.
I'm thinking this has something to do with the Master template.
Re: how to iterate over controls in page to set properties
Hi,
I´m no expert but have you tried puting it in a try/catch? Without catching the exeption.
Dim ctlControl As System.Web.UI.WebControls.WebControl
For Each ctlControl In Page.Controls
Try
ctlControl.Enabled = False
Catch ex As Exception
End Try
Next