Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find control in page

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?

like image 833
user1263390 Avatar asked Mar 22 '12 20:03

user1263390


2 Answers

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);
like image 190
Hans Avatar answered Oct 05 '22 22:10

Hans


You may try this..

this.Master.FindControl("Content2").FindControl("a");

You may refer this article...

http://www.west-wind.com/weblog/posts/2006/Apr/09/ASPNET-20-MasterPages-and-FindControl

like image 22
Chen G Avatar answered Oct 05 '22 22:10

Chen G