Search code examples
c#asp.netascx

How to load c# ascx user control based on condition?


I am converting an aspx website from separate aspx language pages (utilizing the same code behind) to one main aspx with user controls. I have one user control ascx file for each language, all with the same IDs in them so the same code behind can be used for any of them. How can I conditionalize which one gets displayed to the user without running into compile issues?

use session variable Session["lang"] This is what I have:

<%@ Register TagPrefix="section" TagName="account"      Src="account.ascx" %>
<%@ Register TagPrefix="section" TagName="account_span" Src="account_span.ascx" %>

EDIT: Solution This is what I ended up using in the .aspx

<asp:PlaceHolder ID="PlaceHolder_section" runat="server" />

and what I have in the code-behind: section variable hold each section name and suffix is the language

 PlaceHolder_section.Controls.Add(this.LoadControl(section + suffix + ".ascx"));

Solution

  • You can use the LoadControl-method to load a UserControl dynamically. See this sample for details.
    So in your case, you would have code like this in the CodeBehind (Page Init or Load) of your page:

    MyUserControlType ctrl;
    if (Session["lang"] == "en-US") 
        ctrl = (MyUserControl) LoadControl("~/PathToUserControl/eng.ascx");
    else if (Session["lang"] == "es-ES")
        ctrl = (MyUserControl) LoadControl("~/PathToUserControl/span.ascx");
    else 
        ctrl = null;
    if (ctrl != null)
    {
        // Initialize properties of ctrl
        Controls.Add(ctrl);
    }
    

    Instead of having a long list of ifs or a switch statement, you could name your UserControls after a certain pattern and store a suffix in the session:

    string userCtrlSuffix = ((string) Session["UserControlSuffix"]) ?? "Eng";
    MyUserControlType ctrl = (MyUserControl) LoadControl("~/PathToUserControl/UserControl" + userCtrlSuffix + ".ascx");
    // Initialize properties of ctrl
    Controls.Add(ctrl);
    

    As @samy mentioned in the comments, loading controls dynamically needs to happen early in the page lifecycle in order to handle ViewState correctly and hook up event handlers properly.