Feb 22nd, 2007, 10:59 PM
#1
Thread Starter
Fanatic Member
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.
Attached Images
Last edited by ZeBula8; Mar 3rd, 2007 at 10:58 PM .
Reason: resolved
Feb 23rd, 2007, 12:16 PM
#2
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
Feb 23rd, 2007, 09:04 PM
#3
Thread Starter
Fanatic Member
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.
Feb 26th, 2007, 08:16 AM
#4
Hyperactive Member
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
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width