ASP.NET在回发上添加控件 [英] ASP.NET Add Control on postback

查看:148
本文介绍了ASP.NET在回发上添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经组织了一个简单的形式来强调动态表单的概念。我需要做的是在用户点击添加按钮时向页面添加控件。



我现在有一个简单的计数器,控件创建,当按钮被点击时增加。



起初我以为会像事件处理程序一样调用RecreateChildControls(类继承自CompositeControl) 。这将根据递增的值创建新的控件,但是所有的控制状态都将丢失。我假设这是因为该事件已经在Init&负载阶段。



有没有其他方法可以做到这一点?我可以通过检查Init事件的回发值来获得它的工作,但是这似乎有点麻烦。

解决方案


这样做会根据递增的值创建新的控件,但所有的控制状态都将丢失。


您在页面生命周期中调用功能太晚。状态适用于您的控件加载阶段,因此如果控件在之前没有创建,那么该状态将不会被还原,因为控件在尝试时不存在



您需要在页面的Init事件中创建控件。



个人而言,不是ASP.Net中动态控件的粉丝。他们有自己的位置,但是我经常选择合适的最大数量的允许的控件,最初将它们放在页面上,只有根据需要启用/禁用/隐藏/显示。


I've put together a simple form to highlight the concepts of dynamic forms. What I need to do is add a control to the page when the user clicks the "Add" button.

I have a simple counter at the moment that stores the amount of controls created, which is incremented when the button is clicked.

At first I thought it would be as simple as calling RecreateChildControls (the class inherits from CompositeControl) on the event handler. This does create the new controls based on the incremented value, but all the control state is lost. I'm assuming this is because the event has been fired after the Init & Load phase.

Is there any other way to do this? I can get it to work by inspecting the postback value on the Init event, however this seems to be a little hacky.

解决方案

This does create the new controls based on the incremented value, but all the control state is lost.

You're calling the function too late in the page life cycle. State is applied to your controls for the "Load" stage, and so if the controls are not created before that stage the state won't be restored, because the controls don't exist when it tries to apply the state.

You need to create the controls in the Page's Init event.

Personally, I'm not a fan of dynamic controls in ASP.Net. They have their place, but more often I choose a suitable maximum number of allowed controls, put them all on the page initially, and only enable/disable/hide/show them as needed.

这篇关于ASP.NET在回发上添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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