Search code examples
vb.netpropertiesuser-controlsvisual-studio-2017

Reset multiple UserControl's properties at once


I want to use this Sub so to reset at once some UserControl's properties. As it is, resets only BackColor value of my UserControl. How can I "convert" it so to resets more than one property?

Private Sub ResetControl(ByVal sender As Object, ByVal e As EventArgs)
    Dim _UserControl As UserControl1 = CType(Me.Control, UserControl1)
    Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)("BackColor")
    _PropertyDescriptor.ResetValue(_UserControl)
End Sub

Solution

  • You can always get all properties and execute this for each of them

        For Each OneProperty In _UserControl.GetType.GetProperties()
            Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)(OneProperty.Name)
            If _PropertyDescriptor.CanResetValue(_UserControl) AndAlso _PropertyDescriptor.GetValue(_UserControl) IsNot Nothing Then
                _PropertyDescriptor.ResetValue(_UserControl)
            End If
        Next
    

    or from list of string if u wanna use names

        Dim ListOfPropertyNames As New List(Of String) From {"BackColor", "BorderStyle", "Dock"}
        For Each OneProperty In ListOfPropertyNames
            Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)(OneProperty)
            If _PropertyDescriptor.CanResetValue(_UserControl) Then ' this return tru if can be reset
                If _PropertyDescriptor.GetValue(_UserControl) IsNot Nothing Then ' check value if is not  nothing
                    _PropertyDescriptor.ResetValue(_UserControl)
                End If
            End If
        Next