Results 1 to 4 of 4

Thread: how to iterate over controls in page to set properties

  1. #1

    Thread Starter
    Fanatic Member ZeBula8's Avatar
    Join Date
    Oct 2002
    Posts
    548

    Resolved 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:
    1. Dim ctlControl As System.Web.UI.WebControls.WebControl
    2.         For Each ctlControl In Page.Controls
    3.             ctlControl.Enabled = False
    4.         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 Attached Images  
    Last edited by ZeBula8; Mar 3rd, 2007 at 10:58 PM. Reason: resolved

  2. #2
    Frenzied Member axion_sa's Avatar
    Join Date
    Jan 2002
    Location
    Joburg, RSA
    Posts
    1,724

    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

  3. #3

    Thread Starter
    Fanatic Member ZeBula8's Avatar
    Join Date
    Oct 2002
    Posts
    548

    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.

  4. #4
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    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
  •  



Click Here to Expand Forum to Full Width