tags:

views:

32

answers:

1

I'm looking to create an instance of a user control programatically in a codebehind of a web site*. The only ways I've found to reference the class of the user control programatically have been:

  1. Register the control in the web.config and drop the control on the page (works, but I don't want the control on the page as I want to dynamically add it).
  2. Add a <%@ Reference Control="Name.aspx"> to the aspx page at the top.

Ideally I would want to have any aspx page reference the control without having to put the <%@ Reference> declaration at the top of each page. I know I can "Register" controls in the web.config so I don't have to do that on every page, so I'm wondering if something similar exists for references. I'm almost certain I'm missing something about the whole registering/referencing concept, so perhaps just an explanation of what the best way to do this is in order.

*Web-site type project and not web application if this matters.

+1  A: 

There's some relevant discussion of this issue in the comments thread here: http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx

In my experience -- confirmed by this thread -- programmatic access to user controls is painful in general in the web site project. If you're doing dynamic control instantiation, I think it strengthens the case for using a web application project instead, so you don't need the @Reference.

Reflection might be one way of getting around this, if you're desperate; you could start here: http://geekswithblogs.net/aghausman/archive/2009/04/15/how-to-pass-parameters-to-the-dynamically-added-user-control.aspx

millerjs
Oh well, guess I can't avoid that until we switch to a web app. Thanks.
Ocelot20