【问题标题】:Passing a particular WebControl type as a parameter in VB.net在 VB.net 中将特定的 WebControl 类型作为参数传递
【发布时间】:2009-04-23 22:15:27
【问题描述】:

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

示例: 我在 GridViewRow 的 ItemTemplate 中有一个用户控件。我正在尝试从用户控件中引用 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”不起作用——这就是我要找的。​​p>

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

谢谢各位!

【问题讨论】:

    标签: vb.net parameters types web-controls


    【解决方案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
    

    【讨论】:

    • 谢谢!效果很好!另外,感谢您提醒我使用递归。自从我停止参加 CS 课程以来,我当然没有充分利用它。
    • 很高兴听到。大约一年前我有同样的需求,但找不到我的原始代码,所以把它放在一起,很高兴它起作用了。
    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2019-02-27
    • 2016-08-07
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多