微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB.NET – 通过容器对象中的控件进行迭代

我有一个带有“清除”按钮的表单。

用户点击“清除”时,我想清除窗体上所有可见元素的值。在日期控制的情况下,我想将其重置为当前日期。

我的所有控件都包含在Panel上。

现在我用下面的代码来做这个。有没有比手动检查每个控件类型更简单的方法?这种方法似乎过于笨重。

更糟糕的是,为了递归地清除子容器(即面板内的组框)中的控件,我必须用重载的“GroupBox”版本重复整个怪物。

编辑:感谢您的建议,以下代码大大简化。

Private Sub btnClear_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnClear.Click
    'User clicks Clear,so clear all the controls within this panel
    ClearallControls(panMid,True) 'True indicates that yes,i want to recurse through sub-containers
End Sub

ClearallControls(ByRef container As Panel,Optional Recurse As Boolean = True)   
  'Clear all of the controls within the container object
  'If "Recurse" is true,then also clear controls within any sub-containers
  Dim ctrl As Control
  For Each ctrl In container.Controls
      If (ctrl.GetType() Is GetType(TextBox)) Then
          Dim txt As TextBox = CType(ctrl,TextBox)
          txt.Text = ""
      End If
      If (ctrl.GetType() Is GetType(CheckBox)) Then
          Dim chkbx As CheckBox = CType(ctrl,CheckBox)
          chkbx.Checked = False
      End If
      If (ctrl.GetType() Is GetType(ComboBox)) Then
          Dim cbobx As ComboBox = CType(ctrl,ComboBox)
          cbobx.Selectedindex = -1
      End If
      If (ctrl.GetType() Is GetType(DateTimePicker)) Then
          Dim dtp As DateTimePicker = CType(ctrl,DateTimePicker)
          dtp.Value = Now()
      End If

      If Recurse Then
          If (ctrl.GetType() Is GetType(Panel)) Then
              Dim pnl As Panel = CType(ctrl,Panel)
              ClearallControls(pnl,Recurse)
          End If
          If ctrl.GetType() Is GetType(GroupBox) Then
              Dim grbx As GroupBox = CType(ctrl,GroupBox)
              ClearallControls(grbx,Recurse)
          End If
      End If
  Next
End Sub

@Theraccoonbear:我喜欢你的建议,但是当我将声明更改为:

Private Sub ClearallControls(ByRef controls As ControlCollection,Optional ByVal Recurse As Boolean = True)

然后这一行给我“无法转换类型为”ControlCollection“的对象键入”ControlCollection“。:

ClearallControls(panMid.Controls)
您可以跳过与 TryCast的GetType和CType舞蹈:
Dim dtp as DateTimePicker = TryCast(ctrl,DateTimePicker)
If dtp IsNot nothing then dtp.Value = Now()

这将节省大约10行。

一个extension method关闭控制类应该保持它很整洁:

<Extension()> _
Public Shared Sub ClearValue(c as Control,recursive as Boolean)
   Dim dtp as DateTimePicker = TryCast(c,DateTimePicker)
   If dtp IsNot nothing Then dtp.Value = Now()
   ' Blah,Blah,Blah
End Sub

编辑:如果以为忽略NullReferenceExceptions的邪恶扩展方法的想法不会让你感到沮丧:

<Extension()> _
Public Shared Sub ClearValue(c as CheckBox)
   If c IsNot nothing Then c.Checked = False
End Sub

TryCast(ctrl,CheckBox).ClearValue()

原文地址:https://www.jb51.cc/vb/256024.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐