简体   繁体   English

如何从单个.ascx文件在ASP.net页中加载多个用户控件

[英]How to load multiple user controls in ASP.net page from a single .ascx file

I try to use custom control with .ascx file to load mutliple controls in ASP page, on click button event. 我尝试将自定义控件与.ascx文件一起使用,以在单击按钮事件时在ASP页中加载多控件。

Here is my .ascx file : 这是我的.ascx文件:

<%@ Control Language="VB" ClassName="CHelloWorld" %>
<script runat="server">
</script>

<asp:Panel ID="panel" runat="server">
    hello world!
</asp:Panel>

Now I create a .aspx file with a button, and a panel in which I add controls every time use click on button : 现在,我创建了一个带有按钮的.aspx文件,以及一个每次单击按钮时都会在其中添加控件的面板:

<asp:Panel runat="server" id="panelcontrols">
</asp:Panel>
<asp:Button id="myButton" OnClick="OnClickButton" Text="Add" />

And here is my .vb file with click event : 这是我的带有点击事件的.vb文件:

Sub OnClickButton(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim myControl As Control
    myControl  = LoadControl("myfile.ascx")
    panelcontrols.Controls.Add(myControl  )
End Sub

With this implementation, when I click first time : I see "Hello World!" 使用此实现,当我第一次单击时:我看到“ Hello World!”。 in my page, but when I click second time, third time, ... No change happen ! 在我的页面中,但是当我第二次,第三次单击时,...没有任何变化!

Is it because I can load only one control from .ascx ? 是因为我只能从.ascx加载一个控件吗?

How can I create multiple controls from single .ascx file ? 如何从单个.ascx文件创建多个控件?

Thanks. 谢谢。

[EDIT] [编辑]

OK, I use now WiewState to remember controls already created. 好的,我现在使用WiewState来记住已经创建的控件。 Thanks. 谢谢。

But I have a question : 但是我有一个问题:

My .aspx file use code in .vb file (where I have defined OnClickButton) with this line in @Page directive : Src="[path]/myscript.vb 我的.aspx文件使用.vb文件(我已在其中定义OnClickButton)中的代码,并在@Page指令中使用以下行: Src =“ [path] /myscript.vb

But in this .vb file I don't know how to use CHelloWorld control type, to modify control properties. 但是在此.vb文件中,我不知道如何使用CHelloWorld控件类型来修改控件属性。

If I use this code it doesn't work : 如果我使用此代码不起作用:

Sub OnClickButton(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim myControl As CHelloWorld
    myControl  = LoadControl("myfile.ascx")
    panelcontrols.Controls.Add(myControl  )
End Sub

It fails saying "CHelloWorld" is not defined ! 无法说“ CHelloWorld”未定义!

How can I do ? 我能怎么做 ?

No, it's because you are adding the control dynamically. 不,这是因为您正在动态添加控件。 On each page load the added control will be lost so you need to add it each time (and thus have a way of "remembering" what you added between postbacks) 在每个页面加载中,添加的控件都会丢失,因此您每次都需要添加它(因此可以“记住”回发之间添加的内容)

I'm glad the ViewState worked for you. 我很高兴ViewState为您服务。

Regarding the next issue, have you got the correct namespace? 关于下一个问题,您是否拥有正确的名称空间? (It may be worth asking this in a separate question) (可能值得在另一个问题中提出这个问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM