Question:
How to load a UserControl (ascx) dynamically?Answer:
You can load your ascx using the method GetManifestResourceStream().Follow these steps:
- Load your ascx as stream.
- Read the steam as a string.
- Ask the page to parse the string as a control tree.
- 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:
Post a Comment