在回发时以编程方式添加控件

回发 :如何在我的代码隐藏文件中访问ASP.NET控件,这些文件是以编程方式添加的?

我将一个CheckBox控件添加到占位符控件:

PlaceHolder.Controls.Add(new CheckBox { ID = "findme" }); 

ASPX文件中添加的控件在Request.Form.AllKeys中显示正常,除了我以编程方式添加的控件。 我究竟做错了什么?

在控件上启用ViewState没有帮助。 如果只是那么简单:)

您应该在回发时重新创建动态控件:

 protected override void OnInit(EventArgs e) { string dynamicControlId = "MyControl"; TextBox textBox = new TextBox {ID = dynamicControlId}; placeHolder.Controls.Add(textBox); } 
 CheckBox findme = PlaceHolder.FindControl("findme"); 

你是这个意思吗?

您需要在Page_Load期间添加动态添加控件,以便每次都正确构建页面。 然后在你的(我假设按钮点击)你可以使用扩展方法(如果你使用3.5)来找到你在Page_Load中添加的动态控件

  protected void Page_Load(object sender, EventArgs e) { PlaceHolder.Controls.Add(new CheckBox {ID = "findme"}); } protected void Submit_OnClick(object sender, EventArgs e) { var checkBox = PlaceHolder.FindControlRecursive("findme") as CheckBox; } 

扩展方法在这里找到

 public static class ControlExtensions { ///  /// recursively finds a child control of the specified parent. ///  ///  ///  ///  public static Control FindControlRecursive(this Control control, string id) { if (control == null) return null; //try to find the control at the current level Control ctrl = control.FindControl(id); if (ctrl == null) { //search the children foreach (Control child in control.Controls) { ctrl = FindControlRecursive(child, id); if (ctrl != null) break; } } return ctrl; } }