简体   繁体   中英

@ Reference Control in .aspx, but class not found in respective aspx.cs

Hopefully the title made at least some sense.

I've been fiddling with ASP.NET and C# for the first time today - following a tutorial. I have comfortably got as far as this ; however, when I try to implement:

<%@ Reference Control="~/UserInfoBoxControl.ascx" %>

and

UserInfoBoxControl userInfoBoxControl = (UserInfoBoxControl)LoadControl("~/UserInfoBoxControl.ascx");
userInfoBoxControl.UserName = "John Doe";
userInfoBoxControl.UserAge = 78;
userInfoBoxControl.UserCountry = "Spain";
UserInfoBoxPH.Controls.Add(userInfoBoxControl);

I get

The type or namespace name 'UserInfoBoxControl' could not be found...

My Java background makes me now want to 'import' this control class with using , although I understand the @ Reference does this job. I've attempted some rudimentary troubleshooting by eliminating code from earlier in the tutorial, but with no luck. From what I've read elsewhere, the code looks all okay, so I'm a bit confused and keen to move on in my tutorial :)

Thanks!

Edit:

I'm still at this hurdle, so I thought it would ultimately be easiest to just dump all my code:

Default.aspx

Default.aspx.cs (the error occurs when declaring userInfoBoxControl )

UserInfoBoxControl.ascx

UserInfoBoxControl.ascx.cs

You would import a namespace in the page directive. You register user controls:

<%@ Register TagPrefix="uc1" TagName="UserInfoBox" Src="UserInfoBoxControl.ascx" %>

EDIT: (from my comment) reference the namespace ASP:

using ASP;

If you declared everything correctly, then your code should work.

The Register directive is needed to reference the control in pages, user controls etc.

The Reference directive , instead, "Indicates that another user control, page source file, or arbitrary file located at some virtual path should be dynamically compiled and linked against the current ASP.NET file (Web page, user control, or master page) in which this directive is declared."

It's just a guess, but is it possible that you declared your cotrol in a single file (ie the C# code is not in a separate file) and you forgot the "className" attribute in the @ Control directive?

EDIT : I have seen your code, the problem is that the files are named "UserInfoBoxControl", but the name of the class is WebUserControl :

public partial class WebUserControl : System.Web.UI.UserControl {

Your @Reference directive is importing the file "~/UserInfoBoxControl.ascx", but the type name is WebUserControl.
Try this, it should compile:

WebUserControl userInfoBoxControl = (WebUserControl)LoadControl("~/UserInfoBoxControl.ascx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM