code_junkie

Dynamically Loading a UserControl with LoadControl Method (Type, object[])

Nov 13th, 2011
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. [WebMethod]
  2. public static string LoadAlternates(string productId, string pnlId)
  3. {
  4. object[] parameters = new object[] { pnlId, productId };
  5. return ControlAsString(typeof(PopupControl), parameters);
  6. }
  7.  
  8. private static string ControlAsString(Type controlType, object[] parameters)
  9. {
  10. Page page = new Page();
  11. UserControl controlToLoad;
  12. /*
  13. *calling load control with the type results in the
  14. *stringwriter returning an empty string
  15. */
  16. controlToLoad = page.LoadControl(controlType, parameters) as UserControl;
  17. /*
  18. *However, calling LoadControl with the following overload
  19. *gives the correct result, ie the string rep. of the control.
  20. */
  21. controlToLoad = page.LoadControl(@"~/RepeaterSamples/PopupControl.ascx") as UserControl;
  22.  
  23. //some more code, then this...
  24. page.Controls.Add(controlToLoad);
  25.  
  26. StringWriter sw = new StringWriter();
  27. HttpContext.Current.Server.Execute(page, sw, false);
  28. return sw.ToString();
  29. }
Add Comment
Please, Sign In to add comment