2

Similar questions to this one have been asked but none seem to address my exact situation here's what I am trying to do.

I have a user control that manages student info. i.e. FirstName, LastName, Address etc.

I have a webpage/form that has a button on it. "Add Student". What I want to accomplish is for a new StudentInfo control to be added to the webform after each click.

My current code looks something like this

Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
Dim lStudentInfo as Control

LoadControl("~/StudentInfo.ascx")

Me.placeholder1.controls.add(lStudentInfo)

End Sub

With this code only one StudentInfo control is added and upon pressing the "Add" button again a new StudentInfo control isnt added below the first one and the text/data entered within the first control is cleared.

Thanks in advance for any assistance.

1 Answer 1

5

What is happening is that every time you do a postback your previous control was lost. Remember, every postback uses a brand new instance of your page class. The instance you added the control to last time was destroyed as soon as the http request finished — possibly before the browser even finished loading it's DOM.

If you want a control to exist for every postback you have to add it on every postback.

Additionally, if you want ViewState to work for the control you need to add it before the Load event for the page. This means either on Init or PreInit.

Private Sub btnAddStudent_Click(sender as object, ByVal e As System.EventArgs)
    Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
    Session("NewStudentControls") += 1
End Sub

Protected Sub Page_Init(sender as object, e as system.eventargs)
     For i As Integer = 1 To Session("NewStudentControls")
          Me.placeholder1.controls.add(LoadControl("~/StudentInfo.ascx"))
     Next
End Sub   

Not the answer you're looking for? Browse other questions tagged or ask your own question.