Because of the life cycle of an ASP.NET page, controls are only created by processing the request ( IHttpHandler.ProcessRequest(HttpContext) ).
Before iterating through the controls, you need to execute the following code:
//this is necessary, Otherwise "Default.aspx" will show the contents of "WebForm1.aspx". HttpWorkerRequest hwr = new SimpleWorkerRequest(this.TxtPageVirtualPath.Text, "", tw); HttpContext fakeContext = new HttpContext(hwr); ((IHttpHandler)p).ProcessRequest(fakeContext);
Below is the full code for Default.aspx:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Compilation; using System.Collections.Generic; using System.Resources; using System.IO; using System.Web.Hosting; namespace _1423280WebApp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void BtnLoad_Click(object sender, EventArgs e) { Page p = BuildManager.CreateInstanceFromVirtualPath(this.TxtPageVirtualPath.Text, typeof(Page)) as Page; List<String> controlList = new List<String>(); MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); HtmlTextWriter htw = new HtmlTextWriter(tw);
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_1423280WebApp._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Get List of Controls from:<br /> <asp:TextBox ID="TxtPageVirtualPath" runat="server">~/webform1.aspx</asp:TextBox><br /> <asp:Button ID="BtnLoad" runat="server" OnClick="BtnLoad_Click" Text="Load" /><br /> Controls:<br /> <asp:TextBox ID="TxtListControls" runat="server" Height="328px" TextMode="MultiLine" Width="100%"></asp:TextBox></div> </form> </body> </html>
Solution with full code example: q_11423280WebApp.7z
Hailton
source share