使用For Each修改Collection的副本仍然会出错

时间:2014-04-11 22:49:02

标签: asp.net vb.net

我正在尝试扫描我拥有的一些True / False RadioButtonLists。他们在一个QuestionList中。我试图在每个项目中添加一条消息,说“正确”或“不正确”,但是当我这样做时,我得到“集合被修改;枚举操作可能无法执行。”

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    If (IsPostBack) Then
        Dim SubmittedQuestionsList As New HtmlGenericControl("ol")
        SubmittedQuestionsList = QuestionsList

        For Each QuestionItem In SubmittedQuestionsList.Controls
            If TypeOf QuestionItem Is HtmlGenericControl Then
                For Each question In QuestionItem.Controls
                    If TypeOf question Is RadioButtonList Then
                        Dim QuestionExplanation As New Panel
                        If (question.SelectedValue = "true") Then
                            QuestionExplanation.CssClass = "succcess-response"
                            QuestionExplanation.Controls.Add(New LiteralControl("Correct!"))
                        Else
                            QuestionExplanation.CssClass = "error-response"
                            QuestionExplanation.Controls.Add(New LiteralControl("Incorrect:"))
                        End If
                        'If I uncomment the line below, error goes away
                        QuestionsList.Controls.Add(QuestionExplanation)
                        Debug.WriteLine(question.SelectedValue)
                    End If
                Next
            End If
        Next
    End If
End Sub

循环播放它(或其副本)的最佳方式是什么,并在我去的时候添加一条消息?

1 个答案:

答案 0 :(得分:0)

Per Dave的评论,注意到SubmittedQuestionsList只是对QuestionList的引用,我发现我可以简单地使用一个数组。

替换:

Dim SubmittedQuestionsList As New HtmlGenericControl("ol")
SubmittedQuestionsList = QuestionsList

使用:

Dim SubmittedQuestionsList(QuestionsList.Controls.Count) As HtmlGenericControl
QuestionsList.Controls.CopyTo(SubmittedQuestionsList, 0)