Variable scope and Windows Forms

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a menu that calls another form. I would like to pass the second form
a parameter based on the menu item selected. How can I do that?. A public
variable in the Menu is unavailable in the second form.
 
You could create a new constructor (sub New in VB) overload and pass the
parameter in when you create the form instance. If the second form is
created once and then cached, then you could create an event on the first
form that will notify the second form that something interesting has
happened, or you could set up a property or method on the second form so
that you can push information from the first form when a change has taken
place.
 
Thank you. That sounds good, but I'm a little unclear about how to pass the
parameter. Here is the code in the menu that calls the second form:

Dim newform As New form2
newform.ShowDialog()

So If I want to pass a string to form2 what is the syntax, and what has to
be changed in the class statement of form2. all I have in form2 now is:
Public Class Form2.

Thanks

I'ved tried a few variations putting the parm in ( ) but it doesnt work.
 
If you're creating a new instance of "Form2" every time, then what I would
suggest is as follows.

' This goes in Form1.
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem1.Click
Dim newform As New Form2("Parameter")
newform.ShowDialog()
newform.Dispose()
End Sub

' These go in Form2.
Private obj As String = Nothing
Public Sub New(ByVal obj As String)
MyClass.New()
Me.obj = obj
End Sub

Then just use "obj", or whatever you're going to call it, however you see
fit within the scope of Form2.
 
mh1mark said:
I have a menu that calls another form. I would like to pass the second
form
a parameter based on the menu item selected. How can I do that?. A
public
variable in the Menu is unavailable in the second form.

What you need in 'Form2' is a reference to your instance of 'Form1'. You
can pass the reference to 'Form1' in a property when showing 'Form2' from
'Form1':

Code for 'Form1':

\\\
Dim f As New Form2()
f.Form1 = Me
f.Show()
///

Code for 'Form2':

\\\
Private m_Form1 As Form1

Public Property Form1() As Form1
Get
Return m_Form1
End Get
Set(ByVal Value As Form1)
m_Form1 = Value
End Set
End Property
///

You can access 'Form1''s properties inside 'Form2' with 'Me.Form1', for
example, 'Me.Form1.Button1.Text = "Bla"'.

Providing a reference to an application's main form
URL:http://dotnet.mvps.org/dotnet/faqs/?id=accessmainform&lang=en
 
Back
Top