且构网

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

ASP.NET在回发上添加控件

更新时间:2023-12-06 10:24:22


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


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



您需要在页面的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.