Change it to the following:
public class WebForm1 : System.Web.UI.Page
> {
> protected System.Web.UI.WebControls.Button load1Btn;
> protected System.Web.UI.WebControls.PlaceHolder placeHolder;
> protected System.Web.UI.WebControls.Button load2Btn;
>
> override protected void OnInit(EventArgs e)
> {
> load1Btn.Click += new EventHandler(load1Btn_Click);
> load2Btn.Click += new EventHandler(load2Btn_Click);
Note--> EnsureChildControls();
> }
>
> protected override void CreateChildControls()
> {
> placeHolder.Controls.Clear();
placeHolder.Controls.Add(LoadControl("DynamicContr ol1.ascx"));
placeHolder.Controls.Add(LoadControl("DynamicContr ol2.ascx"));
placeHolder.Controls[0].Visible = false;
placeHolder.Controls[1].Visible = false;
> base.CreateChildControls();
> }
>
> private void load1Btn_Click(object sender, EventArgs e)
> {
> placeHolder.Controls[0].Visible = true;
placeHolder.Controls[1].Visible = false;
> }
>
> private void load2Btn_Click(object sender, EventArgs e)
> {
> placeHolder.Controls[0].Visible = false;
placeHolder.Controls[1].Visible = true;
>
> }
> }
Explanation: (btw, the above scheme is somewhat inefficient)
You are switching the user controls at button click. The new user
control won't receive the button click because the Page RaisePostBack
event has already been fired (thats how you got to the first button
click handler in the first place). This is an event that does not
play 'catch up' for loaded user controls (although Init, OnLoad,
OnPreRender, and a few others do). Your code only works when your
page load just happens to load the same control as you add in the
button click. See
http://aspalliance.com/articleViewer.aspx?aId=134&pId=
for details.
BTW, CreateChildControls is only called when you call
EnsureChildControls (although the framework will call it for you in a
few places). So its not a lifecycle event like the others.
You can load the proper user control on Init if you want to, but that
means either changing a hidden field through javascript in the onclick
handlers of your buttons, and then checking for that field in Init, or
checking Page.Request.Form["__EVENT_TARGET"] for the UniqueID of the
button you clicked. BTW, you are not assigning IDs explicitly when
you add the user controls. You should really do that and use
FindControl instead of indexing them by number like I did above.
If this doesn't solve everything then please ask again.
-Sam