我遇到了这个动态创建控件的代码。我尝试过这个。但是,每当我运行它时,对象引用未设置为对象错误的实例弹出并指向代码中的某一行(我把--->放在行上)。我是这种编程语言的新手。我不知道该怎么做。
这是我得到的代码:
Imports System.Collections.Generic
'Imports System.Data.Odbc
Partial Public Class main
Inherits System.Web.UI.Page
Private controlCounter As Integer = 0
Private myControlList As List(Of String)
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
myControlList = DirectCast(ViewState("myControlList"), List(Of String))
For Each ctlID As String In myControlList
controlCounter += 1
Dim hyper As New HyperLink()
hyper.ID = ctlID
Dim lineBreak As New LiteralControl("<br />")
PlaceHolder1.Controls.Add(hyper)
PlaceHolder1.Controls.Add(lineBreak)
Next
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
myControlList = New List(Of String)()
ViewState("myControlList") = myControlList
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
controlCounter += 1
Dim hyper As New HyperLink()
hyper.Text = "a new text Box"
hyper.ID = "hyperlink" + controlCounter.ToString()
Dim lineBreak As New LiteralControl("<br />")
PlaceHolder1.Controls.Add(hyper)
PlaceHolder1.Controls.Add(lineBreak)
--> myControlList.Add(hyper.ID)
ViewState("myControlList") = myControlList
End Sub
End Class
请帮帮我。感谢。
答案 0 :(得分:2)
单击按钮会启动回发,如果请求不回发,您只需将myControlList
设置为某个内容,所以没有任何内容。
如果你想在页面加载时创建列表,然后只是继续添加它,那么你需要在创建后将myControlList
推送到Session或其他内容中它,然后在按钮上再次单击检索它,添加到它,并在会话中重新设置它。
要执行此操作,请添加和获取会话内容,执行,
Session("someDistinctKey") = myControlList;
myControlList = CType(Session("someDisctintKey"), List(Of String))
分别