Access an object from other forms

microkarl

Well-known member
Joined
Apr 22, 2004
Messages
82
Location
Morristown, NJ
All,
If I declare a new object, say, a Hashtable in Form.Load event, how can I access this object from another form? The worse is, I cant even see this object from other events in the SAME form. Does anyone have any clue?

Thanks,
Carl
 
Class level variables and properties

Variables declared within a method are local to that method only and not from other methods within the same class. To allow the variable to be used by other methods it must be declared at class level:

Code:
Public Class MyForm
    Inherits Form

    Class-level variables
    Private m_htable As Hashtable

    Intantiate within Form_Load
    Private Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        Use m_htable
        m_htable = New Hashtable()
    End Sub

    Use within other methods
    Private Sub Form_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
        Use m_htable
        m_htable.Clear()
    End Sub

End Class

To allow htable to be accessible from outside MyForm it should be exposed using a property. Unless you want other classes to be able to change the actual instance of htable, you should declare the property ReadOnly:

Code:
Public Readonly Property HTable As Hashtable
    Get
        Return m_htable
    End Get
End Property

Good luck :cool:
 
Back
Top