我正在尝试使用aspx页面中包含的所有控件ID来填充列表。
如果我为此目的使用ArrayList,则生成该列表。示例函数:AddControls1。
但是如果我使用泛型List,我会收到NullReferenceException错误。示例函数:AddControls2。
创建通用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
答案 0 :(得分:5)
controlList2 = Nothing
你的失败了。您专门将列表设置为null,然后尝试使用它。
答案 1 :(得分:0)
您将其设置为Nothing,为空
controlList2 = Nothing