Control Iteration : Collection was modified; enumeration operation may not execute.

I'm trying to iterate through a pages controls, and while currently i've been successful setting controls to read only, i'd like to convert them to labels, to make for easy printing. Here is what i have, but when i run it, i get Collection was modified; enumeration operation may not execute.
I know that i'm adding/removing controls so that's why this is happening, but is there a better way to do this then taking the contents of the control, throwing it into a label, removing the original control and then adding the label control to the page?

Public Shared Sub SetFormToReadOnly(ByVal ctrl As System.Web.UI.Control)
            Dim txtTemp As TextBox
            Dim ddltemp As DropDownList
            Dim btnTemp As Button
            'iterate through each control in the page, and each controls' controls to get every
            'control on the masterpage/content page/ and and associated grouped controls, i.e. panels, etc.
            For Each subCtrl As Control In ctrl.Controls
                If TypeOf subCtrl Is TextBox Then
                    txtTemp = subCtrl
                    txtTemp.ReadOnly = True
                    Dim tlabel As New Label
                    tlabel.Text = txtTemp.Text
                ElseIf TypeOf subCtrl Is DropDownList Then
                    ddltemp = subCtrl
                    ddltemp.Enabled = False
                ElseIf TypeOf subCtrl Is Button Then
                    btnTemp = subCtrl
                    btnTemp.Enabled = False
                End If
            Next subCtrl
        End Sub
Who is Participating?
Bob LearnedConnect With a Mentor Commented:
You can't use For Each if you are going to remove controls, you would need to loop through the controls by index:

For index As Integer = 0 To ctrl.Controls.Count - 1
   Dim subCtrl As Control = ctrl.Controls(index)
Next index


I have a page that is divided into panels and then I mark the panel enabled property to false (for certain conditions).  The result is, every control inside of that panel is disabled.  Its kind of an easy blanket thing that works.  The only down side I dont like is that everything is grey, rather than black.  I havent played with styles to see if this is changeable.  That is a solution that doesnt involve changing textboxes to labels, or vice versa.
JimBrandleyConnect With a Mentor Commented:
As Bob said, you need to use an index. However, if you are going to remove some, you have to index from the end to the start or you will skip some. So the index needs to be decremented after each pass through the loop.
Forced accept.

EE Admin
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.