将特定的WebControl类型作为参数传递给VB.net

时间:2009-04-23 22:15:27

标签: vb.net parameters types web-controls

我正在尝试创建一个搜索WebControl的父子关系的函数(基本上与WebControl.FindControl(id为String)相反,但查找特定的WebControl类型)。

实施例: 我在GridTemplate中有一个用户控件,用于GridViewRow。我试图从用户控件引用GridViewRow。用户控件可能是也可能不在div或其他类型的控件内,所以我不确切知道有多少父母要查看(即我不能只使用userControl.Parent.Parent)。我需要一个函数来找到它在父子层次结构上的第一个GridViewRow。

因此需要这个功能。除非有更好的方法来做到这一点? 无论如何,我希望我正在创建的函数是相当通用的,因此可以根据我正在寻找的内容指定不同的WebControl类型(即GridViewRow,Panel等)。这是我写的代码:

Public Function FindParentControlByType(ByRef childControl As WebControl, ByVal parentControlType As WebControl.Type, Optional ByRef levelsUp As Integer = Nothing) As WebControl
    Dim parentControl As WebControl = childControl
    Dim levelCount = 1
    Do While Not parentControl.GetType = parentControlType
        If Not levelsUp = Nothing AndAlso levelCount = levelsUp Then
            parentControl = Nothing
            Exit Do
        End If
        levelCount += 1
        parentControl = parentControl.Parent
    Loop
    parentControl.FindControl(
    Return parentControl
End Function

我知道函数定义中的“ByVal parentControlType as WebControl.Type”不起作用 - 这正是我要找的。

我确信有更好的方法可以做到这一点,所以请随意指出我看起来很简单!

谢谢大家!

1 个答案:

答案 0 :(得分:1)

您应该能够使用递归轻松完成此操作。这是一个让你开始或可能解决问题的例子。

在VB语法上不再那么好了,但我确信你可以通过转换器运行它(比如converter.telerik.com)

C#代码

public T FindParentControl<T>(
    ref WebControl child, 
    int currentLevel, 
    int maxLevels)
    where T : WebControl
{
    if (child.Parent == null || currentLevel > maxLevels)
        return null;

    if (child.Parent is T)
        return child.Parent as T;
    else 
        return FindParentControl<T>(
            child.Parent, 
            currentLevel + 1, 
            maxLevels);
}

VB.NET代码(由converter.telerik.com提供)

Public Function FindParentControl(Of T As WebControl)(
    ByRef child As WebControl,
    currentLevel As Integer, 
    maxLevels As Integer) As T

    If child.Parent = Nothing OrElse currentLevel > maxLevels Then
        Return Nothing
    End If

    If TypeOf child.Parent Is T Then
        Return TryCast(child.Parent, T)
    Else
        Return FindParentControl(Of T)(child.Parent, currentLevel + 1, maxLevels)
    End If
End Function