寻找指定型别的父控件

一般我们可以使用 FindControl 去找到子控件,但是若我们需要去找指定型别的父控件要如何寻找呢?例如去寻找指定 TextBox 控件所属的 UpdatePanel 父控件。针对上述的需求,以下将提供解决方式。
在 Control 有一个 Parent 属性,表示该控件的父控件,所以我们可以利用递归方式逐层往上判断 Parent 属性是否为指定型别,符合的话传回该父控件。以下的 FindParent 函式就是在寻找指定型别的父控件。
     '''   <summary>
    
'''  尋找指定型別的父控制項。
    
'''   </summary>
    
'''   <param name="Control"> 控制項。 </param>
    
'''   <param name="Type"> 欲尋找的型別。 </param>
     Public   Shared   Function  FindParent( ByVal  Control  As  Control,  ByVal  Type  As  System.Type)  As  Control
        
If  Control.Parent  Is   Nothing   Then
            
Return   Nothing
        
Else
            
If  Type.IsInstanceOfType(Control.Parent)  Then
                
Return  Control.Parent
            
Else
                
Return  FindParent(Control.Parent, Type)
            
End   If
        
End   If
    
End Function

 

如果要寻找 TextBox 所属的 UpdatePanel 则可以撰写如下程序代码即可。

 

         Dim  oParent  As  Control
        oParent 
=  FindParent(TextBox1,  GetType (UpdatePanel))

你可能感兴趣的:(控件)