0

I have a problem similar to Variable with Value of a Label Name

But instead of a label, I am trying to use a ListBox

    Private Sub processLog(ByVal logFileName As String, ByVal logCateory As String)
    Dim variableListBox As New ListBox

    variableListBox = DirectCast(Me.Controls(logCateory), ListBox)
    variableListBox.Items.Add("HELLO")

    End Sub

What could possible be wrong with the above code, it return NullReferenceException was unhandled Object reference not set to an instance of an object. on the line, variableListBox.Items.Add("HELLO").

I have also a timer to call the above Sub:

    Private Sub tmrProcessLogs_Tick(sender As Object, e As EventArgs) Handles tmrProcessLogs.Tick
       processLog(fileGeneral, lbxGeneral.Name.ToString)
    End Sub
2
  • Probably there's no control named logCateory in the container, a debugger could help you to find the exact problem. Commented Nov 28, 2013 at 8:24
  • the logCategory is the variable use to pass the name of the control. When the timer ticks, a sub is called with parameters in which the second parameter is the name of the control Commented Nov 28, 2013 at 8:27

1 Answer 1

1

The most likely reason is that the parent of the given control is not the Main Form and, as far as Me.Controls("name") only looks for controls whose parent is the Main Form, variableListBox is Nothing and thus you trigger the error while intending to access Items.Add("HELLO"). Replace

variableListBox = DirectCast(Me.Controls(logCateory), ListBox)
variableListBox.Items.Add("HELLO")

With:

Dim ctrls() As Control = Me.Controls.Find(logCateory, True)
If (ctrls.Count = 1 AndAlso TypeOf ctrls(0) Is ListBox) Then
     variableListBox = DirectCast(ctrls(0), ListBox)
     variableListBox.Items.Add("HELLO")
End If

All this by assuming that logCateory contains the name of one of the controls in the form (a parent or a child at any level).

Sign up to request clarification or add additional context in comments.

2 Comments

the same error: Object reference not set to an instance of an object.
@PaulPolon This is impossible. This code avoids this to happen (even in case of not finding any control called logCateory). Please, post the code you have tried. It might not find anything but variableListBox =... is only reached in case of finding the right control and thus the error you refer will never be triggered (it might be the case that nothing happens)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.