形式是动态创建的页面空 [英] Form is Null in Dynamically created Pages

查看:70
本文介绍了形式是动态创建的页面空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个动态页面在ASP.NET中,我要加载的表单内的控制,但每次我尝试将它添加到Page.Form.Controls的形式为空,并给出了一个NullReference

I'm creating a Page Dynamically in ASP.NET and i want to load a Control inside the form but everytime I try to Add it to Page.Form.Controls the Form is null and gives out a NullReference

Page myPage = new Page();
FormAtt ctrl = (FormAtt)myPage.LoadControl("path/to/my/file.ascx");
myPage.Form.Controls.Add(ctrl);


我试图做到这一点,因为我要解析HTML控件,而射击的事件和控制内部的逻辑,成一个字符串来填充HTML code一(非常糟糕的设计)字符串,如果我只是叫 ctrl.RenderControl(的HTMLWriter)控件将不会呈现,看来,该事件不会被触发,我猜我必须有一个页面,该事件流动的工作,但我真的不希望创建一个新的aspx只是这一点。


I'm trying to do this because I have to parse the controls HTML , while firing the events and the logic inside the control, into a string to fill a (really bad designed) String with HTML code, if I just call ctrl.RenderControl(HtmlWriter) the control will not render and it appears that the Events are not fired, i guessed i had to have a page to make the the event flow work, but I really didn't want to create a new aspx just for this.

另外,我敢肯定的路径是正确的,因为我测试相同loadcontrol并为因为...当我改变的东西不存在的路径提出了不引发异常。我不能重新设计code的组装HTML,因为它只是太多的工作,这是出了什么事情我做的范围并不决定的范围由我。

Also, I'm sure the path is correct because I tested the same loadcontrol and becaus it doesn't raise an exception as it raises when I change the path to something non-existant. I can't redesign the code that assembles the HTML because it's just too much work and It's out of the scope of what i'm doing, the scope is not decided by me.

推荐答案

看起来像用户控件文件的路径是不正确的。

Look like UserControl file path is not correct.

你可以试试这个

string path = HttpContext.Current.Request.ApplicationPath == "/" ? 
   string.Empty : HttpContext.Current.Request.ApplicationPath;

... (FormAtt)myPage.LoadControl(path + "/path/to/my/file.ascx");

如果它仍然无法正常工作,在那里你file.ascx位于与您的aspx页面?

If it still doesn't work, where is your file.ascx located related to your aspx page?

更新:myPage.Form永远是零。请实例化的HtmlForm。

Page myPage = new Page();
HtmlForm form = new HtmlForm();
FormAtt ctrl = (FormAtt)myPage.LoadControl("path/to/my/file.ascx");
form.Controls.Add(ctrl);
myPage.Controls.Add(form);

这篇关于形式是动态创建的页面空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆