在每次回发时重新添加处理程序

时间:2011-06-08 16:31:14

标签: asp.net vb.net

加载页面时,调用以下代码

页面加载

Dim products As New LinkBut​​ton

products.Text =“产品”

testPanel.Controls.Add(产品)

AddHandler products.Click,AddressOf getProducts

getProducts函数

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

当我点击链接的链接创建产品时,我想要实现的产品当我点击产品链接时,它会调用事件处理程序调用getProducts。 getproducts将在数据库中循环以获取所有记录,然后当我点击它应该调用另一个事件的产品名称时,它将为每个产品名称创建一个链接。我的问题是如何在每次回发后添加控件谢谢你

1 个答案:

答案 0 :(得分:0)

由于链接是动态创建的,因此您必须在每次回发时为它们重新创建并重新添加处理程序。

在_init事件中,您必须检查您所处的状态(在产品加载之前或产品加载之后),然后创建产品加载链接或产品详细信息链接。关键是必须在每次回发时创建它们并且必须在_Load事件之前创建它们。通常,这应该在_Init事件中完成。

有些事情如下:

        Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init

    If ViewState.Item("ProductsLoaded") IsNot Nothing Then
        If ViewState.Item("ProductsLoaded").ToString = "True" Then
            GetProducts(Me, New EventArgs)
        Else
            CreateProductsButton()
        End If
    Else
        CreateProductsButton()
    End If
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub CreateProductsButton()
    Dim btnProducts As New LinkButton
    btnProducts.Text = "Products"
    testPanel.Controls.Add(btnProducts)
    AddHandler btnProducts.Click, AddressOf GetProducts
    ViewState.Item("ProductsLoaded") = False.ToString
End Sub

Private Sub GetProducts(sender As Object, e As EventArgs)
    ' get products list here
    ' and set handlers for each link
    ViewState.Item("ProductsLoaded") = True.ToString

End Sub

Private Sub GetProductsDetails(sender As Object, e As EventArgs)
    'get product details here
End Sub