I try to use custom control with .ascx file to load mutliple controls in ASP page, on click button event.
Here is my .ascx file :
<%@ 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 :
<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 :
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!” 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 ?
How can I create multiple controls from single .ascx file ?
Thanks.
[EDIT]
OK, I use now WiewState to remember controls already created. 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
But in this .vb file I don’t know how to use CHelloWorld control type, to modify control properties.
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 !
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)