Reputation: 808
I have a user control "UserApplianceControl" that I need to dynamically add to a asp page.
I am doing so with the following code:
User.aspx.cs
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
A5Lib.User u;
UserServiceReference.UserServicesClient myProxy = new UserServiceReference.UserServicesClient();
u = myProxy.GetUser("user1");
if (listOfAppliances != null)
{
foreach (A5Lib.Appliance str in u.Appliances)
{
UserApplianceControl uac = (UserApplianceControl)LoadControl("UserApplianceControl.ascx");
uac.setAppliance(str);
Panel1.Controls.Add(uac);
}
}
}
In UserApplianceControl, I have several buttons. However, whenever I press a button, the user control's button handler is never called. In fact OnLoadComplete(above) gets called first, and so those controls populated on the last page load are recreated and I lose the old ones before I can handle the event.
Why isn't the event firing before OnLoadComplete?
Upvotes: 1
Views: 1478
Reputation: 6249
You are recreating your controls too late in the page lifecyle.
A dynamically added control must be present (loaded) no later than onInit for any viewstate/postback functionality to work.
Move your code to the page's OnInit event. This will ensure that all the controls are rebuilt BEFORE viewstate is restored and the page does all it's button/event hooking up.
Upvotes: 2