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

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

asp.net - FindControl and INamingContainer

I want to word this question carefully, so helpful people don't jump in and spend their time telling me information that I already know (I don't want to waste their time).

I want to understand how FindControl works in ASP.NET web application projects (the ones where the c# files are referenced as CodeBehind, NOT CodeFile, in the markup).

Code behind have two files which sit between the markup file. E.g. Default.aspx will have Default.aspx.cs and Default.aspx.designer.cs

If you put a button on a page, it is added to the designer file. For example: protected global::System.Web.UI.WebControls.LinkButton LinkButton1;

If you want to get a reference to that control, it is immediately available as a member of the Default class. E.g. this.LinkButton1.Text = "Click Me";

If you look at a trace for the page, it is given a unique id as per the behaviour for INamingContainers (here, the Page): ctl00$ContentPlaceHolder1$LinkButton1

The thing I don't understand is why a null is returned by the statement: Control c = Page.FindControl("LinkButton1");

I realise this is unnecessary, as the button is already available to the Default class. And this is because it appears as a member in the Default.aspx.designer.cs file.

The thing I do not understand is why null is returned. Because the Page implements INamingContainer, and the button has an ID which correlates to that expected of a control in an INamingContainer. Isn't this exactly the kind of thing FindControl finds?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

FindControl is not recursive, and it looks like you have an intermediary ContentPlaceHolder1 control, which is a naming container, so this should work: Page.FindControl("ContentPlaceHolder1").FindControl("LinkButton1")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...