I'm at a loss why this is not working and other questions and answers here has not lead me to an answer.
I have a simple project with 2 listboxes. One is named lList and the other is named lListH.
The below works:
function MyFunction (byval lList as listbox, byval lListH as listbox)
lList.Items.Add("Visible list")
lListH.Items.Add("Hidden List")
end Function
Whereas the below is what I'd like to use, but it doesn't work:
function MyFunction (byval lList as listbox)
Dim sControlName = lList.Name & "H"
Debug.Print(sControlName) 'Outputs lListH as expected
Dim lListH As ListBox = CType(Me.Controls(sControlName), ListBox)
lList.Items.Add("Visible list")
lListH.Items.Add("Hidden List") 'error on this line: System.NullReferenceException, 0x80004003
end Function
CodePudding user response:
The most likely explanation is that the ListBox is not directly on the form but, rather, is in some other container, e.g. a Panel. That means that it is in the Controls collection of that container, not that of the form. You can also call the Find method of the form's Controls collection to search it and its children. Note that that will return a Control array, because there could be multiple controls with the same name in different containers.
