动态生成控件的事件处理 [英] Event handling for dynamically generated controls

查看:62
本文介绍了动态生成控件的事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个模块,基本上可以使用XSLT在页面上动态生成所有控件.它们将被渲染并添加到正确的标记中.这里的问题是我想为此动态生成的控件编写事件处理,而且我不确定该如何实现,因为在完美的开发环境中,我们通常双击aspx页面上的控件,.NET为您创建一个相关事件在aspx.cs页面的背面.

I am working on a module where I am basically generating all the controls on the page dynamically using XSLT. They are being rendered and added to the mark up right. Here the problem is that I want to write event handling for this dynamically generated controls and I am not sure how to achieve that because in perfect development environment, we normally double click on our control on aspx page and .NET creates a related event for you in the back on the aspx.cs page.

有什么想法吗?

推荐答案

您需要使用适当的处理程序创建一个方法,并在创建它们时将其连接到动态创建的控件.

You'll need to create a method with the appropriate handler and wire it up to your dynamically created controls when you create them.

protected void MyHandler(object sender, EventArgs e)
{
    //Do some stuff
}

创建控件时

LinkButton lb = new LinkButton();
    lb.ID = "lbexample";
    lb.Click += MyHandler;
Page.Form.Controls.Add(lb);

但是非常重要的是,在回发时,请按原样重建这些控件,否则事件将不会触发.您需要首先重新创建控件,以便引发事件,因此,必须使用自己喜欢的任何状态机制在回发中提供创建控件所需的任何数据.

But it's very important that on your postback, you rebuild these controls as they were or the event won't fire. You'll need to recreate the controls first so that the event can be raised, so any data that you'll need to create the controls will have to be available on the post back using whatever state mechanism you're comfortable with.

这篇关于动态生成控件的事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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