Form is Null in Dynamically created Pages

2019-08-27 16:39发布

问题:

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);

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.

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.

回答1:

Look like UserControl file path is not correct.

Could you try this

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

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

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

Updated: myPage.Form will always be null. Please instantiate 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);


回答2:

Page myPage = new Page(); is almost definitely not what you want here. It sounds like you want to load your control into the current page, which would just be Page.Controls.Add(ctrl).

Your title and question are both pretty clear about creating a Page though, so maybe you should explain the big picture more.