Dynamically Loading User Controls

Sometimes, based on conditional statements, we may need to load one or more user controls, dynamically – like –
if condition #1 is true then
load control1
else
load control2
end if

This sample shows how to do this, based on three controls (First.ascx, Second.ascx, and Third.ascx)

The only code in each of theses User Control Files is in the following format:

<hr>
<div align=”center”><b><i>This is the First Control</i></b></div>
<hr>

Naturally, change the text for each User Control. Save each one with the file names above. Then, copy the code below to a new page. Also make note (from the code) that the files are in a directory called ‘aspnet’, off the root directory of your web site.

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Conditional Controls</title>
<script language="VB" runat="server">
Dim strLoad as string
Sub doit(Source as Object, E as EventArgs)
strLoad="/aspnet/" & rb1.selecteditem.text & ".ascx"
Dim myControl as Control=CType(Page.LoadControl(strLoad), Control)
ph1.Controls.Add(myControl)
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<asp:RadioButtonList id="rb1" runat="server">
<asp:listitem id="First" Value="First" runat="server"/>
<asp:listitem id="Second" Value="Second" runat="server"/>
<asp:listitem id="Third" Value="Third" runat="server"/>
</asp:RadioButtonList><br>
<asp:Button id="button1" Text="Load Controls" onclick="doit" runat="server" />
</Form>
<asp:placeholder ID="ph1" runat="server"></asp:placeholder>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>