相同类型的多个用户控件添加到页面 [英] Add Multiple User Control of the Same Type to a Page

查看:142
本文介绍了相同类型的多个用户控件添加到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似问题,这一个被邀请,但没有似乎解决我确切的情况这里就是我想要做的。

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.

我有一个网页/表单上有一个按钮。 添加学生。我想做到的是每次点击后,被添加到Web窗体新StudentInfo控制。

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.

我目前的code看起来像这样

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

通过这个code添加只有一个StudentInfo控制在$ P $再次pssing添加按钮下方的第一个和文本增加了一个新StudentInfo控制心不是/第一个控件中输入的数据将被清除。

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.

推荐答案

正在发生的事情是,每次你做一个回发你的previous控制时间丢失了。记住,每一个回发使用您的网页类的全新实例。实例添加的控制,最后一次是的摧毁的尽快http请求完成—可能是浏览器之前,甚至完成加载它的DOM。

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.

此外,如果你想的ViewState为控制工作,你需要在Load事件之前增加它的为页的。这意味着,init或preINIT无论是。

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

这篇关于相同类型的多个用户控件添加到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆