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 UserCo开发者_JAVA百科ntrol _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.
精彩评论