解决User Control中某某control无法找到的Compile Error
以前用VS2008 Express写了一个UserControl,没有namespace,应用过程中没有遇到任何问题。
但是现在在做另外一个项目的时候改用VS2008 Team Suite,而且项目用到了自定义的namespace,这个时候,我尝试把之前写好的那个UserControl加到现在这个项目中的**.aspx文件中,结果编译时报错,提示说找不到命名空间。在UserControl中加入自定义的namespace之后,问题解决。
但是另外一个问题又冒出来了,编译时,编译器报错,提示说UserControl中的控件无法找到,提示信息如下:
Error 1 The name 'lblScript' does not exist in the current context E:\×××\Msger.ascx.cs 99 13 MyNameSpace
但是我的UserControl中明明有这个控件啊,而且在CodeBehind文件中,智能感知也是正常的。当时郁闷了很久,后来在网上搜索了一圈,在国外某网站中找到了解决此问题的办法。
因为我们用VS向UserControl中添加control的时候,理论上说,VS应该会自动为我们配置该control的相关基本信息,但是有时候VS也会“偷懒”,这时候就需要我们自己向UserControl的CodeBehind文件中添加这些信息了。
以解决我这个问题为例,编译器说找不到lblScript这个控件,原因是因为在CodeBehind中VS没有替我们自动生成这个控件的定义代码,那我们自己手动加上去就完了:
CodeBehind:
namespace MyNameSpace
{
public partial class Msger : System.Web.UI.UserControl
{
//关键是要自己手动添加这一句
protected System.Web.UI.WebControls.Label lblScript;
protected void Page_Load(object sender, EventArgs e)
{
//然后就可以正常使用控件了
lblScript.Text = "Hello World!"
}
}
}
{
public partial class Msger : System.Web.UI.UserControl
{
//关键是要自己手动添加这一句
protected System.Web.UI.WebControls.Label lblScript;
protected void Page_Load(object sender, EventArgs e)
{
//然后就可以正常使用控件了
lblScript.Text = "Hello World!"
}
}
}
HTML:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Msger.ascx.cs" Inherits="MyNameSpace.Msger" ClassName="Msger" %>
<asp:Label ID="lblScript" runat="server" Text=""></asp:Label>
<asp:Label ID="lblScript" runat="server" Text=""></asp:Label>