First, I have function to flatten all controls on a Control:
Protected Function GetAllControls(Optional ownerControl As Control = Nothing) As IEnumerable(Of Control)
Dim ret = New List(Of Control)()
For Each child As Control In If(ownerControl, Me).Controls
ret.AddRange(GetAllControls(child))
Next
ret.Add(ownerControl)
Return ret
End Function
Then, I want to hide certain buttons on a control using this code:
Dim buttons = GetAllControls().Where(Function(c) c.Name.StartsWith("subButton"))
For Each ctrl As Control In buttons
ctrl.Visible = False
Debug.WriteLine("Hid button " & ctrl.Name)
Next
Yet, after four buttons – the correct count – have been hidden, I get a NullReferenceException, with VS2012 highlighting the lambda expression.
What could possibly cause this?
The last line in your first function adds
ownerControl, which is null the first time you call it, so its adding a Nothing to the list. In your lambda you’re doing ac.Namewhich will throw an exception whencis Nothing.