我遇到与Variable with Value of a Label Name
类似的问题但我没有使用标签,而是尝试使用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
上述代码可能出现问题,它会在NullReferenceException was unhandled
行返回Object reference not set to an instance of an object.
variableListBox.Items.Add("HELLO")
。
我还有一个计时器来调用上面的Sub
:
Private Sub tmrProcessLogs_Tick(sender As Object, e As EventArgs) Handles tmrProcessLogs.Tick
processLog(fileGeneral, lbxGeneral.Name.ToString)
End Sub
答案 0 :(得分:1)
最可能的原因是给定控件的父级不是Main Form
,并且只要Me.Controls("name")
只查找父级是主窗体的控件,variableListBox
是Nothing
因此您在打算访问Items.Add("HELLO")
时触发错误。取代
variableListBox = DirectCast(Me.Controls(logCateory), ListBox)
variableListBox.Items.Add("HELLO")
使用:
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
所有这一切都假设logCateory
包含表单中某个控件的名称(父级或任何级别的子级)。