zoukankan      html  css  js  c++  java
  • FindControl方法误区和解析

    在ASP.NET中Control都有一个FindControl方法,其作用是根据ID(注意既不是UniqueID也不是ClientID)在Control所在的命名容器中寻找相应控件,但实际使用中存在很多误区和陷阱,下面谈谈个人对此的理解:

    1.  认为FindControl方法寻找的范围是给定Control的后代控件。

    1      <form id="form1" runat="server">
    2 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    3 <asp:Panel ID="Panel1" runat="server">
    4 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    5 <asp:Button ID="Button1" runat="server" Text="Button" />
    6 </asp:Panel>
    7 </form>

    如上面代码,后台用Panel1.FindControl("Button1")寻找,认为这样范围小些可以提高效率,其实即使用TextBox1.FindControl("Button1")也一样能找到。前有所述,FindControl方法是根据ID在Control所在的命名容器中寻找相应控件。当执行TextBox1.FindControl("Button1")时,ASP.NET先获取TextBox1.NamingContainer,其值为页面本身(最后生成的xxxx_aspx类实例),再向下递归寻找相应ID的控件,所以一样能找到Button1。

    同样的,如果用TextBox1.FindControl("Label1")也是能找到Label1的。

    2.   不理解为什么this.FindControl方法找不到GridView里的控件。

    其实很好理解,FindControl方法寻找时只在本命名容器下寻找,不会进入其他命名容器中寻找,而命名容器(NamingContainer)不只是页面本身,还包括GridViewRow、DataListItem、RepeaterItem、UserControl、MasterPage等等诸多控件,这些都继承了INamingContainer接口,它们的一个显著特征是其子控件的UniqueID和ClientID一般都不同于ID(除了顶层的页面对象)。

    3.认为FindControl运行效率差。

    实际上ASP.NET运行时分析aspx、ascx、master等文件标签结构,生成类似Dom的控件树,一般对树的查询操作效率还是比较高的,尤其当问题规模不太大时。一般来说,实际页面里的控件数量不可能成千上万,而且寻找时又不能越过本命名容器,这些因素限制了问题规模。所以说FindControl的效率并不差。

  • 相关阅读:
    Linux 如何改变文件属性与权限: chgrp, chown, chmod
    Linux 路径与命令搜寻顺序
    Log level with log4j and Spark
    java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
    max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
    JavaScript Promise异步实现章节的下载显示
    npm-folders
    the user operation is waiting for building workspace to complete解决办法
    Eclipse,新建web项目后 出现jax-ws webservice
    ServletContext在tomcat启动的时候创建
  • 原文地址:https://www.cnblogs.com/dalmeeme/p/2317320.html
Copyright © 2011-2022 走看看