1

I am fairly new to vb.net and am wondering if I am doing any of this right.

In my program, I created a custom control (CustomControl), which and has a custom property (CustomProperty).

Within the program, I have a For Each statement that checks each CustomControl within a form and changes the value of CustomProperty if certain criteria is met:

For Each _CustomControl as Control in Controls
    If TypeOf _CustomControl is CustomControl and [criteria met]
        _CustomControl.CustomProperty = value
    End If
next

Whenever I type in the third line, it gives me the following message:

'CustomProperty' is not a member of 'Control'.

I understand that my custom property does not typically belong to 'Controls', and I was wondering if there is something that I should add to the code or if I should type it in some other way.

I appreciate any help that you can offer.

Alfonso Tienda
  • 3,442
  • 1
  • 19
  • 34

2 Answers2

2

You have to use AndAlso on your condition:

For Each _CustomControl As Control In Controls
    If TypeOf _CustomControl Is CustomControl AndAlso [criteria met]
        _CustomControl.CustomProperty = value
    End If
Next

You try to access the CustomProperty on the default Control. With AndAlso the second part of the condition is not evaluated if the first part isn't true.

You can find some explanations about the difference between And and AndAlso on StackOverflow.

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
2

The answer given is fine, but a better way is to filter out the unneeded controls beforehand using OfType. This makes the type check unnecessary.

For Each _CustomControl in Controls.OfType(Of CustomControl)
    If [criteria met]
        _CustomControl.CustomProperty = value
    End If
Next

If you don't want to use that, than you need to cast to the CustomControl type before attempting to access CustomProperty like so:

For Each _CustomControl As Control In Controls
    If TypeOf _CustomControl Is CustomControl And [criteria met]
        DirectCast(_CustomControl,CustomControl).CustomProperty = value
    End If
Next
A Friend
  • 2,750
  • 2
  • 14
  • 23