2014-02-08 212 views
-1

我正在頁面上動態創建一個按鈕。現在我想使用該按鈕上的按鈕單擊事件。我怎樣才能做到這一點在VB.net & asp.net?如何在動態按鈕上創建動態按鈕點擊事件 - VB.net

我的代碼:

頁面加載:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 
      Try 
       LoadControls() 
      Catch ex As Exception 

      End Try 
     End Sub 

負載控制

Private Sub LoadControls() 
    Try 
     Dim ButtonTable As New HtmlTable 
     Dim ButtonTableRow As New HtmlTableRow 
     Dim ButtonTableCell As New HtmlTableCell 
     Dim btnCode As New Button 
      btnCode.ID = "btnCode" 
      btnCode.Text = "btnCode" 
      AddHandler btnCode.Click, AddressOf btnCode_Click 
     ButtonTableCell.Controls.Add(btnCode) 

     ButtonTableRow.Cells.Add(ButtonTableCell) 
     ButtonTable.Rows.Add(ButtonTableRow) 

     ControlsPlaceHolder.Controls.Add(ButtonTable) 
Catch ex As Exception 

     End Try 
    End Sub 

事件處理程序

Private Sub btnCode_Click(sender As Object, e As EventArgs) 

      Dim buttonId As New Button 
      Try 
       buttonId = DirectCast(sender, Button) 

       // My execution 
      Catch ex As Exception 

      End Try 
     End Sub 

問題:

事件處理程序不會出現.. !!它拋出一個錯誤

Multiple controls with the same ID were found

什麼不對這個代碼.. !!

回答

2

創建動態按鈕後「訂閱」的事件處理程序btnCode_Click到按鈕的事件:

AddHandler btnCode.Click, AddressOf btnCode_Click 

然後EventHandler必須至少Protected,但你是Private - 它不能被訪問,然後

+0

有你看過我的代碼?我在代碼中有這部分代碼,但它不起作用 –

+0

你有一個用'AddHandler ...'行檢查事件處理程序的名字的錯字 – Fabio

+0

不,這不是問題在這裏,發佈錯誤時發佈它在這裏.. !! –