具有控件值的变量

时间:2013-11-28 07:37:48

标签: vb.net .net-3.5

我遇到与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

1 个答案:

答案 0 :(得分:1)

最可能的原因是给定控件的父级不是Main Form,并且只要Me.Controls("name")只查找父级是主窗体的控件,variableListBoxNothing因此您在打算访问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包含表单中某个控件的名称(父级或任何级别的子级)。