2

hello everyone i just start programming in asp.net i struggling to add event handler dynamically. here is the scenario when the aspx page is load a link button is add with an event handler

page load add link button and event handler with link button


Dim products As New LinkButton

products.Text = "Products"

testPanel.Controls.Add(products)

AddHandler products.Click, AddressOf getProducts


the getProducts function will loop in the database get all the product

    Dim testDb As New Product
    Dim arr As ArrayList = testDb.DbLoop()
    Dim ObjList As ProductBo
    Dim ID As Integer
    Dim link As LinkButton



    For Each ObjtList In arr

        ID= ObjtList.C_Id
        link = New LinkButton
        testPanel.Controls.Add(New LiteralControl("<br />"))
        link.ID = ID
        link.Text = ObjList.Name
        link.CommandArgument = CustInt
        Me.testPanel.Controls.Add(link)
        AddHandler link.Click, AddressOf getProductsDetails
    Next ObjList

HERE IS MY problem after looping it will display a list of product in the database, what i want to do add a link of each product name when i click on one product it should invoke another event handler i try this one but it not working.

AddHandler link.Click, AddressOf getProductsDetails

thank you

Milas
  • 347
  • 2
  • 7
  • 16

5 Answers5

3

Don't forget you must re-create all dynamic controls on postback

Your Page is just a class remember and it is instantiated once per request, if it doesn't recreate these controls as well as the associated handlers on the postback request then you won't get anything happen..

You need to recreate these controls prior to Page_Load, you can do this in Page_Init or override the CreateChildControls method.

Richard Friend
  • 15,800
  • 1
  • 42
  • 60
2

The reason it is not working is you are going through a postback. You have to re-add your handler on every postback. I would do it on the page _Init event.

Robert Beaubien
  • 3,126
  • 4
  • 22
  • 29
1

Interchange the following line:

Me.testPanel.Controls.Add(link)
AddHandler link.Click, AddressOf getProductsDetails

They should be:

AddHandler link.Click, AddressOf getProductsDetails
Me.testPanel.Controls.Add(link)
Hasan Fahim
  • 3,875
  • 1
  • 30
  • 51
0

Try this:

Protected Sub page_init(ByVal sender As Object, ByVal e As System.EventArgs)  Handles Me.Init 'addhadler must in here!
    somecode...
End Sub
Senjuti Mahapatra
  • 2,570
  • 4
  • 27
  • 38
0
   Protected Sub page_init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init 
    addButton()'必须加在此处,否则动态注册的事件无法初始化
End Sub

Public sub addButton(ByVal nvrid As Integer) As Object
'.....
        AddHandler btn.Command, AddressOf testCmd
End sub
    Private Sub testCmd(source As Object, e As CommandEventArgs)
        Debug.Print(e.ToString)

End Sub
Gandhi
  • 11,875
  • 4
  • 39
  • 63