Reputation: 2227
I have a Web Application project which has the below structure
ProjectName
-Controls
--WebControls
--MyControl.ascx
-CustomerControls
--CustDetails.ascx
In the CustDetails.ascx control i am trying to load MyControl.ascx, so i have added a reference on the page (not codebehind) i.e.
<%@ Register Src="../Controls/WebControls/MyControl.ascx" TagPrefix="Ctrl" TagName="CustCtrol" %>
The page loads without errors.
I now add the below code to codebehind
LoadControl = Page.LoadControl("MyControl.ascx");
but i receive "The file '/MyControl.ascx' does not exist."
I try changing the path to
~/Controls/WebControls/MyControl.ascx
but same error. Changed it to
../Controls/WebControls/MyControl.ascx
then get "Cannot use a leading .. to exit above the top directory."
I've tried variations and searched google but i cant understand where ive gone wrong?
Edit 1
Upvotes: 3
Views: 2731
Reputation: 880
Pay attention to the directory structure here:
ProjectName
-Controls
--WebControls
--MyControl.ascx
It says that MyControl.ascx is inside Controls directory, not WebControls.
You have 2 options:
1) move MyControl.ascx to WebControls directory, rebuild solution and these codes will work:
<%@ Register Src="~/Controls/WebControls/MyControl.ascx" TagPrefix="ctrl" TagName="CustControl" %>
and
LoadControl = Page.LoadControl("~/Controls/WebControls/MyControl.ascx");
2) keep it in the same directory as you listed( MyControl.ascx in Controls directory) and change path in above codes to these:
<%@ Register Src="~/Controls/MyControl.ascx" TagPrefix="ctrl" TagName="CustControl" %>
and
LoadControl = Page.LoadControl("~/Controls/MyControl.ascx");
No need to use Server.MapPath.
Also, if you have public methods or properties defined in MyControl code behind class, you need to cast the loaded control to MyControl in order to access those methods and properties just like I did here:
LoadControl = Page.LoadControl("...") as MyControl;
//or
LoadControl = (MyControl)Page.LoadControl("...");
Upvotes: 2