在页面中查找控件

HTML

 

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

这段代码工作正常。

但是,这段代码:

HTML

        

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

此代码不起作用, FindControl返回Null – 为什么这样?

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

a的ID更改为ctl00_ContentPlaceHolder1_a – 如何找到控件?

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

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

你可以尝试这个..

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

你可以参考这篇文章……

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

如果要查找的页面没有母版页

 this.Page.Master.FindControl("ContentPlaceHolder1"); 

其他

 this.Page.Master.FindControl("ContentPlaceHolder1").FindControl("controlAFromPage"); 

这可能是由于ASP.NET如何为嵌套控件命名客户端ID。 查看页面源代码,确切了解ASP.NET命名控件的内容。

例如,查看我的页面,我可以看到内容占位符中的按钮呈现如下:

  

在这种情况下,FindControl(“ctl00 $ ContentPlaceHolder1 $ btn1”)返回对Button的引用。

控件是嵌套的。 你有你的页面,在页面内有更多的控件,其中一些控件包含控件本身。 FindControl方法只搜索当前的命名容器,或者如果你执行Page.FindControls,如果只查找Page中的控件,而不是那些控件中的Controls,那么你必须递归搜索。

如果您知道该按钮位于内容占位符内,并且您知道其ID,则可以执行以下操作:

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

或者,如果您的控件是深层嵌套的,您可以创建一个递归函数来搜索它:

 private void DisplayButtonText(ControlCollection page) { foreach (Control c in page) { if(((Button)c).ID == "a") { Response.Write(((Button)c).Text); return null; } if(c.HasControls()) { DisplayButtonText(c.Controls); } } 

最初你会通过这个Page.Controls

 ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.Master.FindControl("ContentPlaceHolder1"); Button img = (Button)cph.FindControl("btncreate_email"); 

要在其他页面上查找母版页控件,我们可以使用:

 Button btnphotograph = (Button)this.Master.FindControl("btnphotograph"); btnphotograph.Text="Hello!!"; 

这应该在页面上找到任何控件

 private Control FindALL(ControlCollection page, string id) { foreach (Control c in page) { if (c.ID == id) { return c; } if (c.HasControls()) { var res = FindALL(c.Controls, id); if (res != null) { return res; } } } return null; } 

打电话给:

 Button btn = (Button)FindALL(this.Page.Controls, "a"); btn.Text = "whatever"; 

查看控件的ID实际上是否呈现为“a”。 在页面加载时使用firebug或开发人员工具。 您可以将客户端ID模式更改为静态,并且每次都获得相同的ID。