代码之家  ›  专栏  ›  技术社区  ›  TheVillageIdiot

在一个页面中工作但在其他页面中不工作的用户控件

  •  0
  • TheVillageIdiot  · 技术社区  · 15 年前

    我以前也提出过这个问题 here .我又面临同样的问题。我有一个用户控件,它显示来自某个业务对象的信息。我已经用了两页了。在这两个页面中,我调用一个带有业务对象的方法,将用户控件上的控件(主要是ASP标签)绑定到对象的属性。我在ASPX页的LoadComplete方法中调用此方法。

      protected void Page_LoadComplete(object sender, EventArgs e)
      {
          control.LoadData(bussinessObject);
      }
    

    这两页都很好用。现在我有了第三页,我使用的是同一个控件。现在当我呼唤 加载数据 在这个新的页面上 空引用 例外:

     Object reference not set to an instance of an object.
     Description: An unhandled exception occurred during the execution of the 
         current web request. Please review the stack trace for more information 
         about the error and where it originated in the code.
    
     Exception Details: System.NullReferenceException: Object reference not set 
       to an instance of an object.
    
     Source Error:
    
     Line 91:             lblOrgName.Text = obj.Name;
    

    编辑: lblorname为空:(请帮助我!

    编辑2: 我跨过了密码。在包含页面的页面加载后,调用masterpage的页面加载,然后调用问题控件的页面加载。在页面加载函数的右大括号()处停止,我在即时窗口中键入了lblorgname,它显示为空。 :(

    然后在包含用户控件的页面的LoadComplete中,我停止并在即时窗口中键入控件的名称。它将其中的所有标签和其他控件显示为空。

    编辑3:

    我已经将受保护的构造函数放入了用户控件中,正如 Stendhal 答案如下:

     protected OrgInfo(){ }
    

    现在我得到这个错误:

     Compiler Error Message: CS0122: 'Controls.OrgInfo.OrgInfo()' is inaccessible 
                 due to its protection level.
    

    项目根目录中的aspx页和orginfo控件位于controls文件夹中。

    编辑4:

    我尝试在页面加载方法中创建所有控件(主要是标签),但是遗憾的是,控件集合的计数是0(零)!

    3 回复  |  直到 15 年前
        1
  •  2
  •   Per Erik Stendahl    15 年前

    如何将用户控件放到页面上?这在过去发生在我身上,原因是不小心将控件添加为服务器控件而不是用户控件。控制中的所有子控件都从未设置。

    您可以通过在用户控件的代码隐藏中放置受保护的默认构造函数来检查这一点:

    受保护的myUserControl()

    这样,控件就不能实例化为服务器控件。

        2
  •  2
  •   TheVillageIdiot    15 年前

    我在页面中添加了以下行:

     <%@ Register src="~/Controls/OrgInfo.ascx" TagName="OrgInfo" TagPrefix="proj1"/>
    

    它工作!

        3
  •  0
  •   dan richardson    15 年前

    听起来好像控件“lblorname”正试图分配一个值,但它尚未构建/解析到ASPX页中。

    确保在有问题的ASPX页的@page指令中设置了以下内容:

    AutoEventWireup="true"