简体   繁体   中英

ASP.NET dynamically load control

I am using the following code to dynamically load a user control from a HttpHandler.

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

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 ie

<div class="content">

<div>
<p>Use the fields below to change your personal details.</p>
<label for="email">Name:</label>
<asp:TextBox CssClass="long" ID="txtProfileName" runat="server" />
<label for="age">Age:</label>
<asp:TextBox ID="txtAge" runat="server" class="tiny" />
<label for="phone">Phone number:</label>
<asp:TextBox ID="txtPhone" runat="server" />
<label for="gender">Gender:</label>
<br />
<asp:DropDownList ID="ddlGender" />
</div>

txtProfileName.Text = "Test";
txtProfileEmail.Text = player.Email;
var genders = new Dictionary<string, string>();
genders.Add("0", "Male");
genders.Add("1", "Female");
ddlGender.DataSource = genders;
ddlGender.DataBind();

I have tried run in debug mode with breakpoints and it's hitting PageLoad for the user control that I'm loading dynamically.

Thanks,

Sean

You should add the control on the init not the load. Otherwise, your controls won't participate in viewstate and events won't be wired properly. Here is an old but valid sample that does what you are trying to do.

http://www.codeproject.com/Articles/7908/Dynamically-Loading-User-Control-on-a-Webform-usin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM