Addhandler, button.click not firing using VB.NET

后端 未结 2 646
南旧
南旧 2021-01-23 12:51

I am experiencing a problem with buttons and AddHandler. It only works if I use AddHandler Button1.click, AddressOf... in Page_load, but if I create the button dynamically in on

2条回答
  •  爱一瞬间的悲伤
    2021-01-23 13:21

    Just to aid anyone who has this problem and isn't quite sure how to implement. Here's a quick example. This example starts out by displaying a dropdownlist. When user selects something from the dropdown, another dropdownlist appears. I typed this off the top of my head, so it MAY contain errors, but you get the idea =)

    In the aspx file, add a placeholder:

    And in your codebehind: ...

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    
        'Store control count in viewstate
        If Not IsPostBack Then ViewState("ControlCounter") = 1
    
        'Rebuild dynamic controls on every postback so when page's life cycle hits Page_Load, 
        'selected values in the viewstate (asp.net default behavior) can be loaded into the dropdowns
        Build_Dynamic_Controls()
    End Sub
    
    Protected Sub Build_Dynamic_Controls()
    
        'Clear placeholder
        myPlaceholder.Controls.Clear()
    
        'This is where the control counter stored in the viewstate comes into play
        For i as Integer = 0 To CInt(ViewState("ControlCounter") -1
            Dim ddlDynamic as New DropDownList With {
                .ID = "ddlDynamicDropdown" & i,
                .AutoPostBack = True
                }
            'This is the event that will be executed when the user changes a value on the form
            'and the postback occurs
            AddHandler ddlDynamic.SelectedIndexChanged, AddressOf ddlDynamic_SelectedIndexChanged
    
            'Add control to the placeholder
            myPlaceholder.Controls.Add(ddl)         
    
            'Put some values into the dropdown
            ddlDynamic.Items.Add("Value1")
            ddlDynamic.Items.Add("Value2")
            ddlDynamic.Items.Add("Value3")
    
        Next i
    End Sub
    
    Protected Sub ddlDynamic_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        'When a dropdown value is changed, a postback is triggered (autopostback=true)
        'The event is captured here and we add another dropdown.
    
        'First we up the control count:
        ViewState("ControlCounter") = CInt(ViewState("ControlCounter")) + 1
    
        'Now that the "total controls counter" is upped by one, 
        'Let's recreate the controls in the placeholder to include the new dropdown
        Build_Dynamic_Controls()
    End Sub
    

    ...

提交回复
热议问题