VB.NET - Iterating through controls in a container object

后端 未结 10 1251
别那么骄傲
别那么骄傲 2020-12-03 05:18

I have a form with a \"Clear\" button.

When the user clicks \"Clear\", I want to clear the value of all the visible elements on the form. In the case of date contro

相关标签:
10条回答
  • 2020-12-03 05:50
    For Each c In CONTAINER.Controls
        If TypeOf c Is TextBox Then
            c.Text = ""
        End If
    Next
    

    Replace the (CONTAINER) by the name of yours (it may be a FORM, a PANEL, a GROUPBOX)
    Pay attention to which you had included your controls in.

    0 讨论(0)
  • 2020-12-03 05:53

    I've done something similar and this is basically how I went about doing it. The only change I might suggest would be instead of overloading the method, just make the passed in type a Control and you can use the same version for GroupBox, Panel, or any other container control that provides a .Controls property. Other than that, I think the definition of "clearing" a control can be somewhat ambiguous and thus there's no Clear() method belonging to the Control class so you need to implement what that means for your purposes for each control type.

    0 讨论(0)
  • 2020-12-03 05:56

    Why not just have one routine

    ClearAllControls(ByRef container As Control, Optional ByVal Recurse As Boolean = True)
    

    You can recurse into it regardless of what level in the hierarchy you begin the call, from the form level down to a single container.

    Also, on the TextBox controls, I use Textbox.Text = String.Empty

    0 讨论(0)
  • 2020-12-03 05:59

    This comes straight from an article discussing techniques to use now that Control Arrays have been done away with going from VB6 to VB.NET.

    Private Sub ClearForm(ByVal ctrlParent As Control)
        Dim ctrl As Control
        For Each ctrl In ctrlParent.Controls
            If TypeOf ctrl Is TextBox Then
               ctrl.Text = ""
            End If
            ' If the control has children, 
            ' recursively call this function
            If ctrl.HasChildren Then
                ClearForm(ctrl)
            End If
        Next
    End Sub
    
    0 讨论(0)
提交回复
热议问题