2011-07-29 26 views
0

我已經在頁面加載上創建了一些動態控件,並添加了一個事件處理程序來處理動態鏈接按鈕的單擊事件。在click事件處理程序的子部分中,我需要引用頁面上的一些其他(非動態)控件並更改它們的值。但是,每次嘗試引用頁面上的控件(本例中爲label1)時,我都會收到空引用異常(對象未設置爲對象的實例)。我在創建這些動態控件或使用我的事件處理程序時做錯了什麼?謝謝!Asp.Net動態控件的事件處理程序的空引用異常

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    'Get the data to populate the controls 
    Dim oMySqlData As New MySqlDataProvider 
     PlaceHolder1.Controls.Add(CreateExistingNotesHTML(oMySqlData.GetParentNotes("104628"), oMySqlData.GetChildNotes("104628"))) 
End Sub 

Public Sub OnCommentClick(ByVal sender As Object, ByVal e As EventArgs) 
    'The event handler for the link buttons 
    Label1.Text = "You clicked " & DirectCast(sender, LinkButton).ID 
End Sub 

Public Function CreateExistingNotesHTML(ByVal dtParent As DataTable, ByVal dtChild As DataTable) As HtmlGenericControl 
    'The routine that creates the dynamic controls 
    Dim divContainer As New HtmlGenericControl("div") 
    For Each drParent As DataRow In dtParent.Rows() 
     divContainer.Controls.Add(WriteNote(drParent.Item("NoteId").ToString(), drParent.Item("UserName").ToString(), drParent.Item("ItemNote").ToString, CDate(drParent.Item("InsertDate")), "note")) 
    Next 

    Return divContainer 

End Function 

Private Function WriteNote(ByVal NoteId As String, ByVal UserName As String, ByVal ItemNote As String, ByVal InsertDate As DateTime, ByVal DivClass As String) As HtmlGenericControl 
    Dim div As New HtmlGenericControl("div") 
    div.ID = "d" & NoteId 
    div.Attributes.Add("class", DivClass) 
div.Controls.Add(New LiteralControl(" · ")) 

    'Add the dynamic link buttons 
    Dim lnkComment As New LinkButton 
    lnkComment.ID = "l" & NoteId 
    lnkComment.Text = "Comment" 
    lnkComment.Style("Text-decoration") = "none" 
    AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick 
    div.Controls.Add(lnkComment) 
Return div 
End Function 

回答

0

這一行

Dim oNotes As New EbayItemNotes  
AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick 

你是你網頁的外部和EbayItemNotes類中處理該事件,請問這個類知道駐留在你的頁面的Label1的東西嗎?

難道說你需要通過你的標籤,以及..

Dim oNotes As EbayItemNotes = new EbayItemNotes(label1) 

EbayItemNotes構造函數中

public sub New(lbl as Label) //store this label for use in event handler.. 
+0

就想通了這一點...這是問題。謝謝! – Tyler

相關問題