0

I'm trying to fill a list with all controls ID contained in an aspx page.

If I use ArrayList for that purpose, that list is generated OK. Example function: AddControls1.

But if I use generic List, I got a NullReferenceException error. Example function: AddControls2.

What I'm doing wrong when creating generic List?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ''success !
        Dim controlList1 As New ArrayList()
        controlList1 = AddControls1(Page.Controls, controlList1)

        For Each str As String In controlList1
            Response.Write(str & "<br/>")
        Next

        ''FAIL
        Dim controlList2 As New List(Of String)
        controlList2 = Nothing
        controlList2 = AddControls2(Page.Controls, controlList2)
        For Each ctl As String In controlList2
            Response.Write(ctl & "<br/>")
        Next
    End Sub

    Private Function AddControls1(ByVal page As ControlCollection, ByVal controlList As ArrayList) As ArrayList
        For Each c As Control In page
            If c.ID IsNot Nothing Then
                controlList.Add(c.ID)
            End If

            If c.HasControls() Then
                AddControls1(c.Controls, controlList)
            End If
        Next
        Return controlList
    End Function


    Private Function AddControls2(ByVal page As ControlCollection, ByVal controlList As List(Of String)) As List(Of String)
        For Each c As Control In page
            If c.ID IsNot Nothing Then
                controlList.Add(c.ID) <-- here I got NullReferenceException error
            End If

            If c.HasControls() Then
                AddControls2(c.Controls, controlList)
            End If
        Next
        Return controlList
    End Function

2 Answers 2

5
controlList2 = Nothing

There's your failure. You're specifically setting the list to null, then trying to use it.

Sign up to request clarification or add additional context in comments.

Comments

0

You are setting it to Nothing which is null

controlList2 = Nothing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.