Question Toggling controls dynamically

RyDog

New member
Joined
Sep 29, 2010
Messages
1
Programming Experience
5-10
Hi,
I'm trying to toggle between controls on a page dynamically. Depending on which button on the page is pushed, a certain control is loaded into the PlaceHolder control. It seems to load each control fine, but after initially loading the control, any data posted from that control is lost on the control's first postback. After the first postback, the control behaves as expected.

Here's my code from the .aspx page:

<asp:Button ID="btnCtrl_1" runat="server" Text="load 1st control" />
<asp:Button ID="btnCtrl_2" runat="server" Text="load 2nd control" /><br />
<asp:placeHolder ID="ph" runat="server"></asp:placeHolder>

and from my code-behind:

Private shared ctrl as System.Web.UI.Control
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not ctrl Is Nothing Then
ph.Controls.Add(ctrl)
End If
End Sub
Private Sub btnCtrl_1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCtrl_1.Click
ctrl = LoadControl("ctrl1.ascx")
ph.Controls.Clear()
ph.Controls.Add(ctrl)
End Sub
Private Sub btnCtrl_2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCtrl_2.Click
ctrl = LoadControl("ctrl2.ascx")
ph.Controls.Clear()
ph.Controls.Add(ctrl)
End Sub

---------------------------------------------------------------
I suspect it has to do with the Viewstate, but I'm not sure. I also tried this with the code from Page_Load in the Page_Init handler, but it made no difference.

I can think of work-arounds, but I'm really wondering why it works the way it does. Thoughts? Suggestions?

Thanks,
Ryan
 
Back
Top