动态创建带有循环的按钮VB.Net [英] Dynamic created Buttons VB.Net with Loop

查看:117
本文介绍了动态创建带有循环的按钮VB.Net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

    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

这不起作用(仅触发PageLoad,而不触发Click事件),但是当我键入

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

    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.

函数updateFunc的标题如下:

The Header of the Function updateFunc is the following:

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

任何想法为何不可行不能和Loop一起工作?
感谢您的回答!

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

推荐答案

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

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

 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

这篇关于动态创建带有循环的按钮VB.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆