带循环的动态创建按钮 VB.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24604297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:49:03  来源:igfitidea点击:

Dynamic created Buttons VB.Net with Loop

vb.netbuttonevent-handling

提问by deru

I have a very strange Problem with dynamic created Buttons in VB.NET: The Click Event is not fired when creating them in a Loop. Here is my code:

我在 VB.NET 中动态创建按钮有一个非常奇怪的问题:在循环中创建它们时不会触发 Click 事件。这是我的代码:

    Panel1.Controls.Clear()
    For i As Integer = 0 To 100 Step 1
        Dim b15 As new Button
        b15.Text = "Test3"
        b15.id = "a" & i
        AddHandler b15.Click, AddressOf updateFunc
        Panel1.Controls.Add(b15)
    Next

This one doesn't work (only the PageLoad is fired, not the Click Event), but when i type

这个不起作用(只有 PageLoad 被触发,而不是 Click 事件),但是当我输入时

    Dim b14 As New Button
    b14.Text = "Test"
    b14.id = "asdf"
    AddHandler b14.Click, AddressOf updateFunc
    Panel1.Controls.Add(b14)

it works fine and the Event is fired.

它工作正常并且事件被触发。

The Header of the Function updateFunc is the following:

函数 updateFunc 的头部如下:

Protected Sub updateFunc(ByVal sender As Object, ByVal e As System.EventArgs)

Any ideas why it doesn't work with the Loop? Thanks for answers!

任何想法为什么它不适用于 Loop?感谢您的回答!

采纳答案by HengChin

Do you include IsPostBackchecking? I assume you did. Try create the control outside.

您是否包括IsPostBack检查?我假设你做到了。尝试在外部创建控件。

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
       'Do Something
    Else
       'Do Something else
    End If

    Panel1.Controls.Clear()
    For i As Integer = 0 To 10 Step 1
        Dim b15 As New Button
        b15.Text = "Test3"
        b15.ID = "a" & i
        AddHandler b15.Click, AddressOf updateFunc
        Panel1.Controls.Add(b15)
    Next
 End Sub

回答by user6177004

flpnlContent.Controls.Clear()
        For i As Integer = 0 To 10
            Dim b15 As New Button
            b15.Text = "a" & i
            b15.Name = "a" & i
            AddHandler b15.Click, AddressOf btn_Click
            flpnlContent.Controls.Add(b15)
        Next

use this it will work

使用它会起作用