For Loop with data Binding

时间:2015-09-01 08:44:20

标签: vb.net webforms

我正在尝试将位置0数据绑定为""在许多下拉列表中,我的代码如下:

For Each ctrl As Control In Me.Controls
    If TypeOf ctrl Is DropDownList Then
        ctrl.DataBind()
        ctrl.items.insert(0, "")
    End If

Next

我收到错误:错误BC30456' items'不是' Control'

的成员

我有点不知所措......请帮忙!

谢谢Tim,那么代码将是什么才能添加""到dropbox .. ..

2 个答案:

答案 0 :(得分:0)

您必须将Control强制转换为DropDownList,否则您无法使用子级DropDownList的属性或方法,只能使用Control

For Each ctrl As Control In Me.Controls
    If TypeOf ctrl Is DropDownList Then  '          <--- Type-Check
        Dim ddl = DirectCast(ctrl, DropDownList)  ' <--- Cast
        ddl.DataBind()
        ddl.items.insert(0, "")
    End If
Next

以下是使用Enumerable.OfType的另一种方式(在文件顶部添加Imports System.Linq):

For Each ddl In Me.Controls.OfType(Of DropDownList)()
    ddl.DataBind()
    ddl.items.insert(0, "")
Next

Control.Controls不会递归返回控件,因此不会嵌套子控件。也许你的DropDownListGridView之类的另一个容器控件中,那么你就不会以这种方式找到它。在这种情况下,正确的方法是处理RowDataBound - 事件并使用GridViewRow.FindControl("drpSite")来获取引用。如果您不能这样做,或者您希望使用递归方式查找所有DropDownLists,则可以使用此扩展方法:

Public Module Extensions
    <Runtime.CompilerServices.Extension()>
    Public Function OfTypeRecursive(Of T As Control)(ByVal root As Control) As IEnumerable(Of T)
        Dim allControls = New List(Of T)
        Dim queue = New Queue(Of Control)
        queue.Enqueue(root)
        While queue.Count > 0
            Dim c As Control = queue.Dequeue()
            For Each child As Control In c.Controls
                queue.Enqueue(child)
                If TypeOf child Is T Then allControls.Add(DirectCast(child, T))
            Next
        End While
        Return allControls
    End Function
End Module

现在很简单:

Dim allDdls As IEnumerable(Of DropDownList) = Me.OfTypeRecursive(Of DropDownList)()

答案 1 :(得分:0)

如果dropDownList已经被限制,则不需要DataBind()。您可以像下面的代码一样将值插入到所需的索引中,您将收到错误,因为Sysetem.web.UI.Controls没有项目。所以你可以通过casting the ctrl as a DropDownList

实现这一目标
   For Each ctrl As Control In Me.Controls
        If TypeOf ctrl Is DropDownList Then
            Dim tempDropDown As DropDownList = DirectCast(ctrl, DropDownList)
            tempDropDown.Items.Insert(0, "")
        End If
    Next