在循环ASP.Net VB中创建时,不会触发动态按钮单击事件

时间:2014-12-14 10:33:17

标签: button dynamic event-handling controls updatepanel

我有同样的问题,但我已在page_Init()事件中声明了所有控件。当我在循环中为动态创建的按钮声明事件处理程序并将其地址设置为x函数时,它不起作用。

有人可以帮忙吗。

以下是我page_Init()中的代码:

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


'Dynamically Load X no. of Updates Panels, and x no. of Controls inside UpdatePanels.

    If (Not Me.DesignMode) Then                 ' Source [Error Creating Control" in the Design View in ] Source : http://tinyurl.com/obutas2

        Dim xLoop As Integer = 5

        For i = 1 To xLoop
            Dim TempUpdatePanel As New UpdatePanel
            TempUpdatePanel.ID = "MyUpdatePanel" & i
            TempUpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional
            UpdatePanelContainer.Controls.Add(TempUpdatePanel)

            Dim TempPanel As New Panel
            TempPanel.ID = "MyPanel" & i
            TempPanel.Width = 500
            TempPanel.Height = 200
            TempPanel.BackColor = Drawing.Color.WhiteSmoke
            TempUpdatePanel.ContentTemplateContainer.Controls.Add(TempPanel)


            For x As Integer = 1 To xLoop
                Dim TempNxt_Button As New Button
                TempNxt_Button.ID = "MyNextButton" & i
                TempNxt_Button.Text = "Next >>"
                AddHandler TempNxt_Button.Click, AddressOf Me.Nxt_btn_Click
                TempPanel.Controls.Add(TempNxt_Button)

            Next

            If TempUpdatePanel.ID = "MyUpdatePanel1" Then
                TempPanel.Style.Add("display", "block")
            Else
                TempPanel.Style.Add("display", "none")
            End If

        Next
    End If

End Sub 

以下是Nxt_btn_Click Event的代码:

Protected Sub Nxt_btn_Click(ByVal sender As Object, ByVal e As EventArgs)

    Dim xLoop1 As Integer = 5

    For i = 1 To xLoop1
        Dim sTempPanel As Panel = FindControl("MyPanel" & i)

        If (sTempPanel Is Nothing) Then
        Else
            sTempPanel.Style.Add("display", "none")
        End If

        Dim sTempPanel1 As Panel = FindControl("MyPanel" & Mid(sender.ID, Len(sender.ID)) + 1)
        If (sTempPanel1 Is Nothing) Then
        Else
            sTempPanel1.Style.Add("display", "block")
        End If
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

找到了修复!

在子循环中创建的按钮是使用公共按钮声明的。即使它们是在不同的UpdatePanel>面板中创建的,它们也分配了相同的ID。我所要做的就是纠正这行代码

从                 TempNxt_Button.ID =“MyNextButton”&我

            TempButton.ID = "Button" & i & "_" & x

此外,子循环使用x作为整数而不是现在的i。