xplosiv_1

Hi,

How do I access variable across forms

Say in form1 I have a variable called Fred that does something: -

x-axis = fred

how do I change the value of fred from form2

Many Thanks,

Andy




Re: Visual Basic Express Edition Simple Question

DMan1

You either need a global reference to form 1 or you need to pass the reference in the forms constructor, or you can have a variable reference to the form in form 2....

Public Class Form1

Public Fred as Double

Private Sub Test()

Dim f2 as New Form2

f2.f1=Me

f2.Show

End Sub

End Class

Public Class Form2

Public f1 as Form1

Public Sub ChangeFred()

f1.Fred=x-axis

End Sub

End CLass






Re: Visual Basic Express Edition Simple Question

ReneeC

 

There are two way to do this. One is Kosher and one is not kosher. In Object oriented programming, one class is not supposed to know about variables in another class. But we know they do.

The simple answer to your question is:  (Remember - a form is a class)

Public Class Form2

    Public Distance as Integer = 0

End Class

Public Class Form1

Public Form1     

Private Sub Form1_Load(ByVal sender As Object, _
                       
ByVal e As System.EventArgs) Handles Me.Load

     Dim Form as New Form2

    Form.Distance = 1

End Sub

ENd Class

But stop and think about it. When you change the size of a form, you know nothing of the variables pertaining to form size. You just know what size you want the form to be, so you relate to it the terms of form properties.

So in OOP there is a proper way to do what you want to do:

Let's call

Public Class Form2

    Public M_Distance as Integer = 0

Public Property NewProperty() As Integer

      Get
       
Return m_Distance
 
End Get

Set(ByVal value As Integer)

       m_Distance = value

End Set

End Property

 

End Class

This is the proper way to do it.