FindControl is not working as expected?

大城市里の小女人 提交于 2019-12-12 01:45:56

问题


I have this structure :

Page
 |
 +---Ascx
      |
      +---<div  runat="server">
                    |
                    +---<asp:button>

I already know that Findcontrol doesn't work recursively .

However when I pressed the button and went to debug and wrote :

this.FindControl("btn1") it did find the "button"

But

  • this= the ascx
  • There is a div runat server which wraps the button

So how did it find it ? According to the definition , it doesn't suppose to work.

Msdn :

Control.FindControl --> The method does not search throughout a hierarchy of controls within controls


回答1:


The asp.net have a different tree struct than the actually DOM of html page.

The controls on the same page are like on the same branch of the tree. So all the controls on the same page can be found by searching the page. The controls that are inside some custom control are also all together.




回答2:


I found the answer.

Only controls which inherits from TemplateControl, which implements the INamingContainer interface.

and obviously <div runat server> is not one of them.

i.e. UserControl :

public class UserControl : TemplateControl, IAttributeAccessor, INonBindingContainer, INamingContainer, IUserControlDesignerAccessor
{...}

i.e. ContentPlaceHolder:

public class ContentPlaceHolder : Control, INonBindingContainer, INamingContainer
{...} 

and here I can see all those controls :



来源:https://stackoverflow.com/questions/15189571/findcontrol-is-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!