在页面中查找控件

use*_*390 10 c# asp.net master-pages

HTML

<body>
    <form id="form1" runat="server">    
       <asp:Button runat="server" ID="a" OnClick="a_Click" Text="apd"/>    
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常.

但是,这段代码:

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>
Run Code Online (Sandbox Code Playgroud)

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

此代码无效并FindControl返回Null- 为什么会这样?

FindControl方法适用于简单的页面,但在母版页中,它不起作用吗?

将ID a更改为ctl00_ContentPlaceHolder1_a- 如何找到控件?

Han*_*ans 31

要在内容页面上找到该按钮,您必须先搜索该ContentPlaceHolder1控件.然后使用控件FindControl上的功能ContentPlaceHolder1搜索您的按钮:

 ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
 Response.Write(((Button)cph.FindControl("a")).Text);
Run Code Online (Sandbox Code Playgroud)