2010-02-12 75 views
1

代码控制我有一些无法找到在超类

<%@ 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 { } 

页和一个超类为他们:

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! 
    } 
} 

为什么没有方法无法找到控制?

+0

这是一个重复http://stackoverflow.com/questions/839794/finding-a-control-in-a--page-from-a-page-base-class –

回答

0

对我来说,你正试图在页面控件集合中找到控件出了什么问题。您必须在Table控件中搜索表格单元格。

Upd。如果您使用母版页,则可以直接从页面访问其控件。首先,你必须声明主类型:

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

然后声明公共财产(可以是一些控制太):

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

然后你就可以写:

string text = Master.MyTitle; 

Master.FindControl('Table1'); 
+0

@sash:尽可能FindControl ()递归搜索它也必须找到我的控制。不是吗? – abatishchev

+1

不,你不能在容器内部控制控件(GridView,ListView,Table等等)。 – sashaeve

+0

为什么如果使用masterpage,this.FindControl(“Table1”)也不起作用。没有它,一切正常。 masterpage是这个邪恶的根源吗? – abatishchev

1

mos我见过的通用解决方案是在控制树下进行递归下降,直到找到具有所需ID的控件为止,例如, http://www.codinghorror.com/blog/archives/000307.html

+0

@flatline:看起来很奇怪,但链接不起作用 - 显示空白屏幕。它现在对你有用吗? – abatishchev

+0

@abatischev - 奇怪,这里同样的事情,但我测试了发布前的链接,并且google缓存仍然有记录。认识这是codinghorror.com的问题?无论如何:http://www.google.com/search?q=findcontrolrecursive都有一些相关的链接 – flatline