[resolved] Dynamic controls disappear on click
This is probably a simple solution, but i can't figure it out......
I dynamically create a control on the page, but it disappears when a button on the page is clicked. Here's an example of what i have:
VB Code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'If Me.IsPostBack = True Then Exit Sub
End Sub
Private Sub btnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOne.Click
Dim chkSample As New CheckBox
With chkSample
.Text = "I was added in the code"
.ID = "chkSample"
.EnableViewState = True
End With
pnlSample.Controls.Clear()
pnlSample.Controls.Add(chkSample)
pnlSample.EnableViewState = True
lblTalk.Text = "button ONE was clicked"
End Sub
Private Sub btnTwo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTwo.Click
lblTalk.Text = "button TWO was clicked"
End Sub
I thought that the controls and their state were supposed to remain, but they don't. Run the page and click the first button - the code runs and creates the checkbox. Then click the second button - the checkbox vanishes.
What am i doing wrong? :confused:
Re: Dynamic controls disappear on click
Dynamically added controls need to be readded at every postback. This article explains the ins and outs:
http://msdn.microsoft.com/library/de.../viewstate.asp
(there is a section in it about dynamically added controls)
The following is on Denis Bauer site as he has created a custom control that recreates dynamic controls on postbacks:
http://www.denisbauer.com/ASPNETCont...aceholder.aspx
i hope this helps
Re: Dynamic controls disappear on click
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Me.IsPostBack Then
call btnOne_Click
end if
End Sub
Private Sub btnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOne.Click
Dim chkSample As New CheckBox
With chkSample
.Text = "I was added in the code"
.ID = "chkSample"
.EnableViewState = True
End With
pnlSample.Controls.Clear()
pnlSample.Controls.Add(chkSample)
pnlSample.EnableViewState = True
lblTalk.Text = "button ONE was clicked"
End Sub
Private Sub btnTwo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTwo.Click
lblTalk.Text = "button TWO was clicked"
End Sub
Re: Dynamic controls disappear on click
well that one wont work..u should initialize every object every postback i guess