Dynamically Loading External Controls from a DropDownList

Displaying a specific web user control (.ascx) from a dropdown selection is a fairly straightforward process.

Create an asp:DropDownList with OnSelectedIndexChanged set to a function. This function will load a user control file based on the selected value of the dropdown. Also, create an asp:PlaceHolder where the control will be placed.

 

       <asp:DropDownList ID=”ddDataTables” runat=”server” AutoPostBack=”true”

OnSelectedIndexChanged=”ddDataTables_Changed” >

         <asp:ListItem Text=”" Value=”"></asp:ListItem>

         <asp:ListItem Text=”More Options” Value=”more_options”></asp:ListItem>

         <asp:ListItem Text=”Address” Value=”address”></asp:ListItem>

 

    <asp:PlaceHolder ID=”phDataTable” EnableViewState=”false” runat=”server” />  

 

And the code behind file looks for a file which is named the same as the selected value (e.g. address.ascx), then adds it to the place holder in the aspx file.

 

    protected void ddDataTables_Changed(object sender, EventArgs e)

    {

        LoadUserControl(ddDataTables.SelectedValue);

    }

   

    protected void LoadUserControl(string strSelectedTable)

    {

        phDataTable.Controls.Clear();

 

        if (strSelectedTable != “”)

        {

            UserControl ucDataTable = (UserControl)LoadControl(strSelectedTable + “.ascx”);

            phDataTable.Controls.Add(ucDataTable);

        }

    }

 

That’s it. A simple way to keep functionality separated in web user controls but be able to still pull them in cleanly when desired.

 

Leave a Reply