2014-03-19 54 views
0

我遇到了可以動態創建控件的代碼。我嘗試過這個。然而,每當我運行它,對象引用未設置爲對象錯誤的實例彈出,並指出代碼中的某一行(我把--->在線上)。我是這種編程語言的新手。我不知道該怎麼辦。未將對象引用設置爲ASP中對象的實例(vb)

這裏是我的代碼:

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 

請幫助我。謝謝。

回答

2

按鈕點擊發起回發,並且如果請求是而不是回發,您只設置myControlList,所以它什麼也沒有。

如果您希望在頁面加載時創建列表,然後只需要繼續添加它並隨後進行點擊,那麼您就需要在創建它之後將myControlList插入到Session或其他內容中,然後點擊按鈕再次獲取它,添加到它,並在會話中重新設置它。

爲此添加和從會議獲得的東西,這樣做,分別

Session("someDistinctKey") = myControlList; 
myControlList = CType(Session("someDisctintKey"), List(Of String)) 

+0

先生,如何推myControlList到會話中? – user3404659

+0

@ user3404659檢查我的更新,希望有幫助。 –

相關問題