2

I have a number of pages

<%@ Page Language="C#" AutoEventWireup="True" CodeBehind="MyPage.aspx.cs" Inherits="MyPage " MasterPageFile="~/Site.master"  %>
<asp:Content ContentPlaceHolderID="commonForm" runat="server">
 <asp:Table runat="server">
  <asp:TableRow>
   <asp:TableCell ID="cellControl" />
  </asp:TableRow>
 </asp:Table>
</asp:Content>

public partial class MyPage : MySuperPage { }

and a super class for them:

public abstract class MySuperPage : Page
{
    public MySuperPage()
    {
        this.Load += new EventHandler(PageLoad);
    }

    // my own method
    protected void PageLoad(object sender, EventArgs e)
    {
        var c = this.FindControl("cellControl"); // null!
    }

    // auto event handling
    protected void Page_Load(object sender, EventArgs e)
    {
        var c = this.FindControl("cellControl"); // null!
    }
}

Why neither method can find this control?

abatishchev
  • 98,240
  • 88
  • 296
  • 433

2 Answers2

1

The most common solution I've seen is to do a recursive descent down the control tree until you find the control with the desired ID, e.g. https://blog.codinghorror.com/recursive-pagefindcontrol/

Cœur
  • 37,241
  • 25
  • 195
  • 267
flatline
  • 42,083
  • 4
  • 31
  • 38
  • @flatline: Looks strange but the link doesn't work - shows blank screen. Does it work for you now? – abatishchev Feb 13 '10 at 09:28
  • @abatischev - weird, same thing here, but I tested the link the before posting, and the google cache still has a record. Methinks it's a problem with codinghorror.com? At any rate: http://www.google.com/search?q=findcontrolrecursive has a number of relevant links – flatline Feb 16 '10 at 02:00
0

Seems to me you are trying to find control in the Page control collection what's wrong. You have to search table cell in Table control.

Upd. If you are using master page you can access its controls directly from page. First you have to declare master type:

<%@ MasterType VirtualPath="~/MasterPage.master" %>

Then declare public property (which can be some control too):

public string MyTitle
{
    get { return "BaseMaster Title"; }
}

Then you will able to write:

string text = Master.MyTitle;

or

Master.FindControl('Table1');
sashaeve
  • 9,387
  • 10
  • 48
  • 61