Monday 18 July 2011

Dot.Net: Loading UserControl ascx Dynamically

Question:
How to load a UserControl (ascx) dynamically?


Answer:
You can load your ascx using the method GetManifestResourceStream().

Follow these steps:
  1. Load your ascx as stream.
  2. Read the steam as a string.
  3. Ask the page to parse the string as a control tree.
  4. Add the resulting control to the control collection of your page.

That's all :)

Here is an example
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    // on charge le contrôle ASCX 
    LoadAscxControl();
}

private void LoadAscxControl()
{
    String content = String.Empty;
    Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), @"MyControl.ascx");
    if (stream != null)
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            content = reader.ReadToEnd();
        }

        if (Page != null)
        {
            Control control = Page.ParseControl(content);
            this.Controls.Add(control);
        }

     }
    else
    {
        // TODO: logging
    }

}



No comments: