0

I want to prepend an aspx page with another page at runtime. I know the better solution would be to use a usercontrol, But for that I would have to put all the elements of my aspx page in a user control & do that for several pages. Isnt there a way to load an aspx page inside another page like a user control? Also I would want to make all the fields readonly of the appended page. Is there a way I can do this?

If usercontrol is the only way, then I have a query. When I loaded my userControl in my PageLoad event, I cannot cast the control to my usercontrol name, & because of that I cannot set a property of my control. I want to do this, but this gives error at compile time:

MyControl myUserControl =(MyControl)Page.LoadControl("~/Controls/MessageControl.ascx");

Here MyControl is not available (It is not recognizable by the compiler) I tried Ctrl+Dot on MyControl, the compiler is not adding any reference to it also, It gives the following error

The type or namespace name 'MyControl' could not be found (are you missing a using directive or an assembly reference?)

When I do this, it works:

 var ctrl = LoadControl("~/Controls/MessageControl.ascx");
                MyPlaceholder.Controls.Add(ctrl);

But now ctrl is not casted which prevents me to set a property of my user control.

Also does it matter If I instantiate the control in Page_Init instead of Page_load? Because in Page_Init I am unable to make a DB call, probably the assemblies/db config hasnt loaded in Page_Init..

zeppelin
  • 451
  • 1
  • 4
  • 24
  • What error do you see at compile time? Add it to your question. Also, verify the definition of your control class, [see this](http://stackoverflow.com/a/31726429/1548894) other question. – zed Aug 18 '15 at 13:13
  • I have added the error in my original question. The full name of my usercontrol class is : "UserControl_MyControl". I tried casting using this also but it was not recognized by the compiler. Currently I have registered it in my .aspx page, After regsitering it in .aspx I can use the control class in my code behind. If am going to add 20 controls dynamically do I have to register all 20 in my .aspx page. Is this the normal behavior? – zeppelin Aug 18 '15 at 14:07
  • Access modifier is also public in my case : public partial class UserControl_MyControl : System.Web.UI.UserControl – zeppelin Aug 18 '15 at 14:11
  • 1
    Yes, you have to `<%@ Register %>` every user control you are going to use. If you are going to use them on many aspx pages, you could register those at your web.config pages->controls section only once for entire site. – zed Aug 18 '15 at 20:21
  • Okay, thanks, I thought that wasn't normal otherwise what is the purpose of dynamically adding controls. Anyway thanks for clarifying. – zeppelin Aug 20 '15 at 10:51

0 Answers0