Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);

}

This code works fine.

However, this 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);
}

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...