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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/vb/256024.html

猜你在找的VB相关文章