Asp.Net 关于FindControl方法使用

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

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

<formid="form1" runat="server"> 
<asp:Label ID="Label1" runat="server"Text="Label"></asp:Label> 
<asp:Panel ID="Panel1" runat="server"> 
<asp:TextBox ID="TextBox1"runat="server"></asp:TextBox> 
<asp:Button ID="Button1" runat="server"Text="Button" /> 
</asp:Panel> 
</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)不只是页面本身,还包括GridViewRowDataListItemRepeaterItemUserControlMasterPage等等诸多控件,这些都继承了INamingContainer接口,它们的一个显著特征是其子控件的UniqueID和ClientID一般都不同于ID(除了顶层的页面对象)。 这块的话大家要注意一下,如果在你所想Find的控件在上面的这类控件里的话,你需要在使用FindControl前加上控件的ID。例如:

<asp:RepeaterID="Repeater1" runat="server" >
       <HeaderTemplate>
            <tableid="Table1"  border="1" cellpadding="0"cellspacing="0" class="printTable">
            <tr >
                <thid="th1">球员ID</th>
                <th>球员姓名</th>
            </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <trid="tr1">
                <td><asp:labelid="label1" runat="server"text='<%#Eval("PL_ID")%>'/> </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>               
       </asp:Repeater>

如果想找到label1的话,需要Repeater1.Items[0].FindControl("label1");这样才可以。

 3.认为FindControl运行效率差。

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

转载:http://bbs.51cto.com/thread-1075841-1.html

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐