【问题标题】:For Loop with data Binding带数据绑定的 For 循环
【发布时间】:2015-09-01 08:44:20
【问题描述】:

我正在尝试在多个下拉列表中将位置 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' is not a member of 'Control'

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

谢谢蒂姆,那么将“”添加到保管箱的代码是什么..

【问题讨论】:

    标签: vb.net webforms


    【解决方案1】:

    如果 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
    

    【讨论】:

      【解决方案2】:

      您必须将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 不递归返回控件,因此不嵌套子控件。也许您的DropDownList 位于另一个容器控件中,例如GridView,那么您不会以这种方式找到它。在这种情况下,正确的方法是处理 RowDataBound-event 并使用 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)()
      

      【讨论】:

      • 谢谢你们,我尝试了这些选项,但没有成功我没有收到错误它只是没有做任何事情我在页面加载子下插入代码...
      • @MardusDavel:那么页面顶部没有DropDownList。也许它在GridView 或其他容器控件中。 Control.Controls 没有查看子控件,因此不涉及递归搜索。您应该向我们展示您的 aspx 的相关部分。
      • 下拉列表>
      • @MardusDavel:如果您添加详细信息,请始终编辑您的问题。但是对于 relevant 部分,我的意思是您应该显示该下拉列表的声明位置,我们还需要查看周围的控件。
      猜你喜欢
      • 2013-09-19
      • 2021-07-23
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多