在基页上使用“FindControl”

我的页面Default.aspxinheritance了BasePage.cs格式。

在基页中,我试图找到实际位于Default.aspx中的控件Label1。

var labelControl = (TextBox)Page.FindControl("Label1"); 

但是,这总是回归为空。 我可以通过基页找到其他页面的控件吗?

FindControl不是递归的(ASP.NET团队由于性能原因没有实现它)。

设置Label的ClientIDMode然后尝试在BasePage.cs中查找标签

  protected override void OnLoad(EventArgs e) { Label lbl = this.FindControl("Label1") as Label; } 

希望这会有所帮助。

如果FindControl()没有结束工作,那么应该可以通过将控件声明为BasePage类中的属性来实现。 假设Default.aspx和其他.aspx页面都将inheritance自BasePage,您应该能够这样做:

 public class BasePage { protected Label Label1; } 

在BasePage方法中,检查您的属性是否为空。 如果是,则控件存在并可以操作:

 protected void SomeBasePageMethod() { if (this.Label1 != null) { // Do something with Label1 } }