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 引用如何为空?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01