how parentForm Reference is null?(parentForm 引用如何为空?)
问题描述
我有一个应用程序,我在表单上添加了一个用户控件.当我在 userControl 构造函数中检查 this.parentForm
时,它给出了一个空引用
I have an application in which i have added a usercontrol on the form.
When i check this.parentForm
in the userControl constructor it gives a null reference
我的 userControl 代码是这样的
My userControl Code is like
public UserControl1()
{
InitializeComponent();
if (this.ParentForm != null)//ParentReference is null
{
MessageBox.Show("Hi");//Does Not get Called
}
}
推荐答案
当控件被创建时,它还没有被添加到表单中——所以父表单当然是空的.
When the control is being created, it won't have been added to a form yet - so of course the parent form will be null.
即使您通常将其写为:
// Where form might be "this"
form.Controls.Add(new UserControl1());
你应该认为它是:
UserControl1 tmp = new UserControl1();
form.Controls.Add(tmp);
现在您的构造函数正在 first 行中执行,但 form
的第一次提及是在 second 行中......所以控件怎么能看到它?
Now your constructor is being executed in the first line, but the first mention of form
is in the second line... so how could the control have any visibility of it?
您可能应该处理 ParentChanged
事件,然后采取适当的行动.(抱歉,如果您没有使用 Windows 窗体 - 我确信其他 UI 框架也有类似的框架;如果您能在问题中说明您使用的内容,下次会很有用.)
You should probably be handling the ParentChanged
event instead, and taking appropriate action then. (Apologies if you're not using Windows Forms - I'm sure there's an equivalent for other UI frameworks; next time it would be useful if you could state what you're using in the question.)
这篇关于parentForm 引用如何为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:parentForm 引用如何为空?


基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01