我使用以下代码从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();
成功加载了PlayerProfile用户控件,但它似乎没有执行设置用户控件中字段值的代码,即
<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();
我尝试在带有断点的调试模式下运行,它正在为我正在动态加载的用户控件点击PageLoad。
谢谢,
肖恩
答案 0 :(得分:0)
您应该在init上添加控件而不是加载。否则,您的控件将不会参与视图状态,并且事件将无法正确连接。这是一个旧的但有效的样本,可以完成你想要做的事情。
http://www.codeproject.com/Articles/7908/Dynamically-Loading-User-Control-on-a-Webform-usin