在超类的代码中找不到控件
我有许多页面
<%@ 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!
}
}
为什么两种方法都找不到此控件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我见过的最常见的解决方案是沿着控件树进行递归下降,直到找到具有所需 ID 的控件,例如 https://blog.codinghorror.com/recursive-pagefindcontrol/
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/
在我看来,您正在尝试在页面控件集合中查找控件出了什么问题。您必须在表格控件中搜索表格单元格。
更新。如果您使用母版页,您可以直接从页面访问其控件。首先,您必须声明主类型:
然后声明公共属性(也可以是某种控制):
然后您将能够编写:
或
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:
Then declare public property (which can be some control too):
Then you will able to write:
or