且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加的按钮不会触发点击事件C#

更新时间:2023-09-29 21:27:52

简而言之,您需要在

In a nutshell, you need to add the button earlier in the Page lifecycle, before the Page_Load event.

正在发生的事情是,对页面的每个http请求都会导致一个全新的页面对象.触发的每个事件都需要一个新的http请求.因此,当触发ViewButton的click事件时,您将从一个全新的Page对象和一个全新的ViewButton开始.为了使一切正常运行,以便新页面具有与旧页面相同的属性,ASP.Net依赖于称为 ViewState 的功能.ViewState信息(通常)与客户端浏览器的http请求一起提交,并用于构建具有与旧控件相同的控件和属性值的新Page对象.

What's happening is that every http request to your page results in a completely new page object. Every event that fires requires a new http request. Therefore your start with a brand new Page object and a brand new ViewButton when the click event for your ViewButton is triggered. To make things work correctly, so that the new page has the same properties as the old, ASP.Net relies on a feature called ViewState. ViewState information is (typically) submitted with the http request from the client's browser, and is used to build a new Page object with the same Controls and property values as the old one.

诀窍是:在处理加载事件之前,在页面 之前还原ViewState.如果在还原ViewState时尚不存在该按钮,则该信息将被丢弃,并且该页面以后将不再知道它需要引发click事件(或者,它会认为没有用于单击的按钮)事件代码首先要运行).

Here's the trick: ViewState is restored for the page before the load event is processed. If the button does not exist yet at the time the ViewState is restored, that information is thrown away, and the page will not later know it needs to raise the click event (or rather, it will think there there is no button for the click event code to run in the first place).

因此,您需要将代码移动到 Pre_Init 事件中,以创建按钮,该事件在 还原ViewState之前运行.

Therefore, you need to move the code to create your button to the Pre_Init event, which runs before the ViewState is restored.

在ASP.Net WebForms中使用动态"控件时,我经常发现以静态方式向页面中添加合理数量的控件并进行全部设置以使其可见,这样更容易.>属性为假.然后,在运行时,我将仅针对需要的控件将 Visible 设置为true.

When working with "dynamic" controls in ASP.Net WebForms, I often find it easier to just add a reasonable number of controls to the page in a static manner and set them all so that their Visible property is false. Then at runtime I will set Visible back to true for just the controls that I need.