Control Iteration : Collection was modified; enumeration operation may not execute.
Posted on 2007-07-24
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