1

My page, Default.aspx inherits form BasePage.cs.

In the base page I am trying to find the control Label1 that is actually in Default.aspx.

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

However, this is always coming back as null. Can I find controls of other pages through the base page?

joncodo
  • 2,298
  • 6
  • 38
  • 74
  • 1
    Label1 is in root of page or in some other control like Panel? Remember that FindControl is not recursive. – Tomas Voracek Sep 27 '11 at 19:21
  • It is in a panel... And the panel is different on each page. The control may be in a panel in another panel on each page. How can I make it generic so that it will find Label1 on any page no matter where it is. +1 for a great catch. – joncodo Sep 27 '11 at 19:28
  • http://stackoverflow.com/questions/253937/recursive-control-search-with-linq – Ta01 Sep 27 '11 at 19:35

3 Answers3

4

FindControl is not recursive (ASP.NET team haven't implemented it for performance reasons).

Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41
1

If FindControl() doesn't wind up working, it should be possible by declaring your controls as properties in your BasePage class. Assuming that Default.aspx and other .aspx pages will all inherit from BasePage, you should be able to do this:

public class BasePage
{
  protected Label Label1;

}

In BasePage methods, check if your properties are not null. If so, the control exists and can be manipulated:

protected void SomeBasePageMethod()
{
  if (this.Label1 != null) 
  {
    // Do something with Label1
  }
}
Shan Plourde
  • 8,528
  • 2
  • 29
  • 42
0

Set the ClientIDMode of the Label & then try to find the label in BasePage.cs

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


}

Hope this will help.

SaQiB
  • 639
  • 8
  • 18