简体   繁体   中英

When I add an custom UserControl to a Panel dynamically, the usercontrol loses all event handling

I've got aspx page which dynamically loads UserControl into a Panel object based on the input on a set of radio buttons. The UserControl successfully adds and displays properly to the Panel on postback and calls the Page_Load() event just fine in the UC but when I interact with the form in any way that would trigger an event, the event is not captured on the postback.

I've tried to add the event handling association in the Page_Load() which I know gets called as well as adding the association in the ASP.NET tag without any difference in result.

This is how I am adding the control (object names have been simplified):

private UserControl _control;

protected void RadioButtonGroup_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton radioButton = (RadioButton)sender;

        if (radioButton == RadioButton1Ctl)
        {
            _control = (UserControl1)LoadControl("~/Controls/UserControl1.ascx");
            PanelCtl.Controls.Add(_control);
        }
        else if (radioButton == RadioButton2Ctl)
        {
            _control = (UserControl2)LoadControl("~/Controls/UserControl2.ascx");
            PanelCtl.Controls.Add(_control);
        }
    }

As I said, the control gets successfully added by when I click any buttons or have any postback events which should be bound on the UC, the control gets removed from the page and events aren't fired.

Any help would be greatly appreciated.

This is happening because the controls are being added dynamically. I would suggest using the DynamicControlsPlaceHolder instead of a Panel. It will persist your controls for you when the page is posted back.

DynamicControlsPlaceHolder: http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

The other alternative is to recreate the controls at every postback, before the ViewState is reloaded. I would suggest using OnInit .

The DynamicControlsPlaceHolder takes all of the hard work away, so that might be the best option for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM