Aspx Load User Control with Params


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //
  2. private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
  3. {
  4. // add this to aspx page that needs to load a .ascx control
  5. // http://www.effegidev.com/post/WebUserControls-and-Parameters.aspx
  6. List<Type> constParamTypes = new List<Type>();
  7. foreach (object constParam in constructorParameters)
  8. {
  9. constParamTypes.Add(constParam.GetType());
  10. }
  11. UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
  12. // Find the relevant constructor
  13. ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
  14. //And then call the relevant constructor
  15. if (constructor == null)
  16. {
  17. throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
  18. }
  19. else
  20. {
  21. constructor.Invoke(ctl, constructorParameters);
  22. }
  23. // Finally return the fully initialized UC
  24. return ctl;
  25. }
  26. //

URL: http://www.effegidev.com/post/WebUserControls-and-Parameters.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.