title: ASP.NET dynamically load control
body: <p>I am using the following code to dynamically load a user control from a HttpHandler.</p>
  
  <pre><code>StringBuilder sb = new StringBuilder();
  StringWriter sw = new StringWriter(sb);
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  Page newPage = new Page();
  newPage.EnableEventValidation = false;
  newPage.LoadControl("~/App_Controls/Site/Player/PlayerProfile2.ascx").RenderControl(htw);
  var content = sb.ToString();
  </code></pre>
  
  <p>The PlayerProfile user control is successfully being loaded but it does not appear to be executing code that sets the values of fields in the user control i.e.</p>
  
  <pre><code>&lt;div class="content"&gt;
  
  &lt;div&gt;
  &lt;p&gt;Use the fields below to change your personal details.&lt;/p&gt;
  &lt;label for="email"&gt;Name:&lt;/label&gt;
  &lt;asp:TextBox CssClass="long" ID="txtProfileName" runat="server" /&gt;
  &lt;label for="age"&gt;Age:&lt;/label&gt;
  &lt;asp:TextBox ID="txtAge" runat="server" class="tiny" /&gt;
  &lt;label for="phone"&gt;Phone number:&lt;/label&gt;
  &lt;asp:TextBox ID="txtPhone" runat="server" /&gt;
  &lt;label for="gender"&gt;Gender:&lt;/label&gt;
  &lt;br /&gt;
  &lt;asp:DropDownList ID="ddlGender" /&gt;
  &lt;/div&gt;
  
  txtProfileName.Text = "Test";
  txtProfileEmail.Text = player.Email;
  var genders = new Dictionary&lt;string, string&gt;();
  genders.Add("0", "Male");
  genders.Add("1", "Female");
  ddlGender.DataSource = genders;
  ddlGender.DataBind();
  </code></pre>
  
  <p>I have tried run in debug mode with breakpoints and it's hitting PageLoad for the user control that I'm loading dynamically.</p>
  
  <p>Thanks,</p>
  
  <p>Sean</p>