Search code examples
vb.netwinformslinqtypedescriptor

Reset all component's properties except excluded ones


I have make a Sub Procedure which gets all the properties of a component into a list and then resets their values, except those I have declare as excluded.

Public Shared Sub ResetPropertiesByComponent(ByVal Component As Component, ByVal ExcludedProperties As String)
    Dim PropertyCollection As List(Of PropertyDescriptor) = TypeDescriptor.GetProperties(Component).OfType(Of PropertyDescriptor).
                                                                           Where(Function(item) item.Name <> ExcludedProperties).
                                                                           ToList()
    For Each _PropertyDescriptor As PropertyDescriptor In PropertyCollection
        If _PropertyDescriptor.CanResetValue(Component) Then
            If _PropertyDescriptor.GetValue(Component) IsNot Nothing Then
                _PropertyDescriptor.ResetValue(_Control)
            End If
        End If
    Next
End Sub

And I use it like this: Call ResetPropertiesByComponent(Me, "ClientSize").

My problem is when I try to make it exclude more than one properties. I changed my Sub Procedure like this:

Public Shared Sub ResetPropertiesByComponent(ByVal Component As Component, ByVal ExcludedProperties As String())
    Dim PropertyCollection As List(Of PropertyDescriptor) = TypeDescriptor.GetProperties(Component).OfType(Of PropertyDescriptor).
                                                                           Where(Function(item) item.Name IsNot ExcludedProperties).
                                                                           ToList()
    For Each _PropertyDescriptor As PropertyDescriptor In PropertyCollection
        If _PropertyDescriptor.CanResetValue(Component) Then
            If _PropertyDescriptor.GetValue(Component) IsNot Nothing Then
                _PropertyDescriptor.ResetValue(_Control)
            End If
        End If
    Next
End Sub

From ExcludedProperties As Stringto ExcludedProperties As String().

And from Where(Function(item) item.Name <> ExcludedProperties) to Where(Function(item) item.Name IsNot ExcludedProperties). As <> is not defined for type String().

And I use it like this: Call ResetPropertiesByComponent(Me, {"ClientSize", "MinimumSize"}).

I get no errors or something, but it does not work too!!! Any idea?


Solution

  • You can use IEnumerable -> Contains

    .Where(Function(item) Not ExcludedProperties.Contains(item.Name))
    

    Have a quick read of the IsNot documentation. It is for comparing object references. It will not error because it is not supposed to, and always returns True because your string and string array won't be the same.