简体   繁体   English

在项目之间使用UserControl时,控件为null

[英]Controls null when using a UserControl between projects

TL;DR: All controls within a usercontrol that's being used outside it's home project are null when that usercontrol's Page_Init/Page_Load methods are called. TL; DR:调用该用户控件的Page_Init / Page_Load方法时,正在其主项目外部使用的该用户控件中的所有控件均为null。

The setup is like this: 设置是这样的:

Projects "UI.Frontend", "UI.ControlPanel", and "UI.Common" are "ASP.NET Web Application"s. 项目“ UI.Frontend”,“ UI.ControlPanel”和“ UI.Common”是“ ASP.NET Web应用程序”。 UI.Common is never meant to be accessed directly- it just contains UserControls that are needed in both the frontend and the control panel. UI.Common绝不能直接访问-它只包含前端和控制面板中都需要的UserControls。

So, an aspx file (SomeFrontendPage.aspx) in UI.Frontend contains the lines: 因此,UI.Frontend中的一个aspx文件(SomeFrontendPage.aspx)包含以下几行:

<%@ Register tagprefix="BP" Namespace="UI.Common" Assembly="UI.Common" %>

and later: 然后:

<BP:MyControl runat="server" ID="ctlMyControl" />

while over in UI.Common, there's a control named MyControl (normal ascx, ascx.cs, and ascx.designer.cs files). 在UI.Common中,有一个名为MyControl的控件(普通的ascx,ascx.cs和ascx.designer.cs文件)。 Now, when I open SomeFrontendPage.aspx in a browser, ctlMyControl gets loaded and it's init+load methods get executed. 现在,当我在浏览器中打开SomeFrontendPage.aspx时,ctlMyControl将被加载,并且它的init + load方法将被执行。 The problem is all subcontrols of MyControl never get initialized. 问题是MyControl的所有子控件都不会初始化。 Example (if MyControl.ascx has a textfield of ID txtBlah): 示例(如果MyControl.ascx具有ID txtBlah的文本字段):

    protected void Page_Init(object sender, EventArgs e)
    {
        txtBlah.Text = "test";
    }

The above code will run, but will cause a null pointer (well, "Object reference not set to an instance of an object") since txtBlah will be null. 上面的代码将运行,但是将导致空指针(好吧,“对象引用未设置为对象的实例”),因为txtBlah将为空。

Edit: An example control would be: 编辑:一个示例控件将是:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="Common.MyControl" %>
Whatever: <asp:TextBox ID="txtWhatever" runat="server"  />

You may find you have more problems that what is immediately shown. 您可能会发现比立即显示的问题更多的问题。 ASCX files aren't embedded in assemblies by default, and when they are, you then need to create a virtual path provider to access them. 默认情况下,ASCX文件未嵌入程序集中,当它们存在时,您需要创建一个虚拟路径提供程序来访问它们。

Can we see an example control? 我们可以看到示例控件吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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