Vb.net 具有控件值的变量
我有一个类似的问题 但我尝试使用列表框而不是标签Vb.net 具有控件值的变量,vb.net,.net-3.5,Vb.net,.net 3.5,我有一个类似的问题 但我尝试使用列表框而不是标签 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("HEL
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未处理
对象引用未设置为对象的实例。
在variableListBox.Items.Add(“HELLO”)
行上
我还有一个定时器来调用上面的子:
Private Sub tmrProcessLogs_Tick(sender As Object, e As EventArgs) Handles tmrProcessLogs.Tick
processLog(fileGeneral, lbxGeneral.Name.ToString)
End Sub
最可能的原因是,给定控件的父控件不是主窗体
,并且就Me.Controls(“name”)
而言,只查找父控件是主窗体的控件,variableListBox
是Nothing
,因此在打算访问项时触发错误。添加(“HELLO”)
。替换
variableListBox = DirectCast(Me.Controls(logCateory), ListBox)
variableListBox.Items.Add("HELLO")
与:
所有这些都是通过假设logCateory
包含表单中某个控件的名称(任何级别的父控件或子控件)。容器中可能没有名为logCateory
的控件,调试器可以帮助您找到确切的问题。logCategory
是用于传递控件名称的变量。当计时器滴答作响时,将使用参数调用sub
,其中第二个参数是控件的名称
相同的错误:对象引用未设置为对象的实例。@PaulPolon这是不可能的。这段代码避免了这种情况的发生(即使在找不到任何名为logCateory的控件的情况下)。请把你试过的代码贴出来。它可能找不到任何东西,但variableListBox=。。。只有在找到正确的控件时才能到达,因此您引用的错误永远不会被触发(可能是什么都没有发生的情况)
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