passing value of variable from one form to another

  • Thread starter Thread starter Stephen
  • Start date Start date
S

Stephen

How do I pass the value of variables created in Form1 to similar named
variables in a second form?

Thanks
Steve
 
Stephen said:
How do I pass the value of variables created in Form1 to similar named
variables in a second form?

Thanks
Steve

"Guessing" as I've not typed it in to check:

Declare variables as "public" in say frm1. Then to pass something from frm2
to frm1: frm1.myVar = 42
 
Well done for asking this, it is a tricky one for new programmers to .NET,
and I don't think Microsoft have ever really articulated how they thought
this "should" be done.

By default a .NET program will shut down if the first form closes, so what I
do is create an instance of the second form from the first form. You can then
either hand the variables through the constructor for the second form, or
simply pass them as Public variables.

The following code shows both methods. Make a new windows form project with
two forms, each with a button, and add the following code:

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Using f As New Form2("Hello")
f.PublicVar = "World"
f.ShowDialog()
End Using
End Sub
End Class

Public Class Form2

Public PublicVar As String

Private mstrVar1 As String

Sub New(ByVal var1 As String)

' This call is required by the Windows Form Designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.
mstrVar1 = var1
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MsgBox("mstrvar1=" & mstrVar1 & "; PublicVar=" & Me.PublicVar)
End Sub
End Class
 
Back
Top