在网页上查找控制

在网页上查找控制

问题描述:

HTML

<body>
    <form id="form1" runat="server">    
       <asp:Button runat="server" ID="a" OnClick="a_Click" Text="apd"/>    
    </form>
</body>

code

protected  void a_Click(object sender,EventArgs e)
{
    Response.Write(((Button)FindControl("a")).Text);

}

这code正常工作。

不过,这code:

HTML

 <%@ Page Title="" Language="C#" MasterPageFile="~/Student/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Student_Default" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button runat="server" ID="a" OnClick="a_Click" Text="andj"/>
</asp:Content>

code

protected void a_Click(object sender, EventArgs e)
{
    Response.Write(((Button)FindControl("a")).Text);
}

这code不工作,的FindControl 收益 - ?这是为什么

This code does not work and FindControl returns Null - why is this?

的FindControl 方法工作在一个简单的页面罚款,但在母版页,它不工作?

The FindControl method works in a simple page fine, but in a master page, does it not work?

的ID的 A 更改为 ctl00_ContentPlaceHolder1_a - 如何能找到控制

The ID of the a is changed to ctl00_ContentPlaceHolder1_a - how can find control?

要找到你所搜索 ContentPlaceHolder1 控制首先在内容页面上的按钮。
然后使用在 ContentPlaceHolder1 控制的FindControl 功能来搜索您的按钮:

To find the button on your content page you have to search for the ContentPlaceHolder1 control first. Then use the FindControl function on the ContentPlaceHolder1 control to search for your button:

 ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
 Response.Write(((Button)cph.FindControl("a")).Text);