usercontrol中的所有控件均为空 [英] All controls are null within usercontrol
问题描述
我有一个使用其他控件的UserControl的UserControl.
I have a UserControl which uses a UserControl, among other controls.
在 ascx
文件中,我具有以下代码:
In the ascx
file I have the following code:
<%@ Register TagPrefix="tag" Namespace="some.name.space" Assembly="some.assembly" %>
<tag:control ID="test" runat="server" />
在我的 Page_Load
方法中,我尝试像这样设置测试的属性:
In my Page_Load
method, I try to set a property on test like so:
test.Text = "Hello World!";
这实际上在我的用户控件 test
中设置了文字控件的Text属性.
This actually sets the Text property of a literal control in my user control test
.
这将引发异常:
对象引用未设置为对象的实例
Object reference not set to an instance of an object
尝试设置
lblTest.Text = value;
为空的对象是 lblTest
.
我没有正确添加用户控件吗?注册代码时,我应该-还是必须-指定 Src
属性?如果是这样,我必须注册我使用的每个用户控件吗?
Am I not adding the user control correctly? Should I - or do I have to - specify the Src
property when registering a Tag? If so, I'd have to register every usercontrol I use?
这也将导致没有任何控件加载到usercontrol中,并且usercontrol中的所有控件均为空.
This also results in no controls loading in usercontrol and all controls are null within usercontrol.
推荐答案
如果用户控件在当前项目中,则需要在注册语句中包含src:
If the user control is in your current project, then you need to include the src in the register statement:
<%@ Register TagPrefix="uc1" TagName="NavTop" Src="controls/NavTop.ascx" %>
但是,如果您在多个页面中使用此用户控件,则也可以在web.config中注册它:
However, if you use this user control in more than one page, then you can also register it in web.config:
<system.web>
<pages>
<controls>
<add tagPrefix="uc1" tagName="NavTop" src="~/controls/NavTop.ascx" />
</controls>
</pages>
</system.web>
要注意的另一件事:在某些情况下,如果仅在源代码视图中进行更改,Visual Studio设计器就不会在页面上看到"对控件的更改.例如,如果更改控件名称,则最终可能会在ascx中使用新名称的控件,而在设计器文件中使用旧名称的控件的引用.在运行时,这将导致设计器文件属性为null.
One other thing to be aware of: there are times when the visual studio designer does not "see" your changes to controls on the page if you only make the changes in source view. If you change a control name, for example, you could end up with a control with the new name in the ascx but a reference to a control with the old name in the designer file. At runtime, this will result in the designer file property being null.
经过多次刻录后,如果我在源视图中进行了任何更改,我将检查以查看设计器文件是否已正确更新,或者我切换到设计视图,进行较小的更改,然后保存页面/用户控件.
After having been burnt by this a number of times, if I make any changes in source view, I either check to see that the designer file has been updated correctly or I switch to design view, make a minor change, then save the page/user control.
这篇关于usercontrol中的所有控件均为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!