0

我正在尝试使用包含在 aspx 页面中的所有控件 ID 填充列表。

如果我为此目的使用 ArrayList,则该列表生成正常。示例函数:AddControls1。

但是如果我使用通用列表,我会收到 NullReferenceException 错误。示例函数:AddControls2。

创建通用列表时我做错了什么?

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
4

2 回答 2

5
controlList2 = Nothing

有你的失败。您专门将列表设置为空,然后尝试使用它。

于 2013-07-05T21:45:46.110 回答
0

您将其设置为空

controlList2 = 无

于 2013-07-05T21:47:35.963 回答