VB ASP动态按钮单击事件未击中处理程序事件 [英] VB ASP dynamic button click event not hitting handler event

查看:78
本文介绍了VB ASP动态按钮单击事件未击中处理程序事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态创建用于分页的按钮,单击这些按钮应调用事件处理程序。回发正在发生,但是它从未命中事件子。
这是我的按钮创建代码(i = 0):

I'm dynamically creating buttons for pagination that should be calling an event handler when clicked. The postback is happening, however it never hits the event sub. This is my button creation code (i = 0):

 Do While (i < pages)
    Dim btn As New Button With {
        .Text = (i).ToString,
        .CommandArgument = (i).ToString,
        .ID = "btnGrdPage_" + (i).ToString
    }

    AddHandler btn.Click, AddressOf Me.btnGrdParticipantPage_Click
    dvPageNumbers.Controls.Add(btn)

    i += 1

Loop

我要单击的事件如下:

The event I'm trying to get to on a click is as follows:

 Protected Sub btnGrdParticipantPage_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim x = 1
    ...
 End Sub


推荐答案

在哪里

记住每个回发都会创建(然后销毁)页面类的全新实例。您不必在发布后保留相同的实例。这意味着用于创建控件的代码必须在每次回发中重新运行。否则,这些控件将不存在,它们将在下一次服务器事件后消失。此外,这必须在页面生命周期的早期完成... 在还原ViewState之前,因为如果此时控件尚不存在,则它们将无法获取更新的ViewState,并且ViewState为页面生命周期如何知道他们需要引发click事件。 Page_Load()为此太晚了。尝试使用 Page_Init() Page_PreInit()

Remember that every postback creates (and then destroys) a brand new instance of the page class. You don't get to keep the same instance from post to post. This means the code to create the controls must re-run on every postback. Otherwise, those controls won't exist, and they'll just disappear after the next server event. Morever, this must happen very early in the page lifecycle... before ViewState is restored, because if the controls don't exist yet at this point, they can't get updated ViewState, and ViewState is how the page life cycle knows they need to raise the click event. Page_Load() is too late for this. Try using Page_Init() or Page_PreInit() instead.

这篇关于VB ASP动态按钮单击事件未击中处理程序事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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