以编程方式添加控件时占位符未实例化
我有一个 ASPX 页面,其中声明了占位符控件。
在代码隐藏中,我创建了一个 UserControl 并将其添加到占位符中。
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = new ChartUserControl();
myForm.Controls.Add(uc);
}
UserControl 反过来有一个占位符,但是在 Page_Load (对于 UserControl)中,当我这样做时:
protected void Page_Load(object sender, EventArgs e)
{
WebControl x = new WebControl();
userControlPlaceholder.Controls.Add(x);
}
它给了我无处不在的“对象引用未设置为对象的实例”异常。
我尝试通过调用构造函数来强制实例化,但这给我带来了其他麻烦。 任何帮助,将不胜感激。
I have a an ASPX Page with a Placeholder control declared.
In the Codebehind I create a UserControl I have and add it to the Placeholder.
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = new ChartUserControl();
myForm.Controls.Add(uc);
}
The UserControl in turn has a Placeholder, but in the Page_Load (for the UserControl) when I do:
protected void Page_Load(object sender, EventArgs e)
{
WebControl x = new WebControl();
userControlPlaceholder.Controls.Add(x);
}
It gives me the ubiquitous "Object reference not set to an instance of an object" exception.
I've tried forcing instantiation by calling a constructor, but that has gotten me into other trouble. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己就花了4个小时。
问题是,您正在创建用户控件,
但必须使用 LoadControl:
显然,LoadControl 会初始化用户控件,以便其占位符(我假设它包含的其他控件)在您使用时不会为空他们。
I just spent 4 hours on this myself.
The problem is that you're creating the user controls with
but you have to use LoadControl:
Apparently, LoadControl initializes the user control so that its PlaceHolders (and I would assume, other controls it contains), won't be null when you use them.
不要在 Page_Load 中添加控件,而是重写 CreateChildControls 方法并将其添加到那里。
Instead of adding the control in the Page_Load, Override the CreateChildControls method and add it there.