How to pass a variable from one winform to another in vb.net

There is often a need to pass a variable from one Winform to another.

There are two scenarios

Let us say you have two forms

1. You opened Form1 and then you want to open a new form called Form2 and you would want to carry some information from Form 1 to Form2.

The user has typed the Employee name  JOHN in the text box on the first form and then clicked on the Lookup Dept. This openes the second lookup form (Form2) where the user can select a Dept Name.

Notice that on the Form2 we have the Employee Name shown ( form1 opened  form2 and passed the value of EmployeeName)

SendVariablefromForm1ToForm2

2. You  have Form1 and Form2 already open and you want to pass a variable from Form2 to Form1

 

Once we select the Dept B on the Form 2 we click on Select and close. The second form (Form2) closes and the value of the selected department Dept B is passed back to the First form (Form1)

 

SendVariablefromForm2toForm1

 

Here is the code for the Form1

 

Public Class Form1
WithEvents fr As New Form2   ‘ Declare the new form using WithEvents
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
fr.lblEmployeeName.Text = Me.TextBox1.Text  ‘ Send the value of Textbox1 to the second Form
fr.Show()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub fr_GetDepartment() Handles fr.GetDepartment   ‘ This is the new Event which has been declared and raised from Second Form

Me.TextBox2.Text = fr.ListBox1.SelectedItem.ToString  ‘ The Listbox selected item value has been received from the second form

End Sub
End Class

Here is the code for Form2

 

 

Public Class Form2
Event GetDepartment()   ‘ You declare this Event for this Form which can be trapped from Form1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me.ListBox1
.Items.Add(“Dept A”)
.Items.Add(“Dept B”)
.Items.Add(“Dept C”)
End With
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RaiseEvent GetDepartment()   ‘ We raise the event here in Form2 which will provide you an opportunity to trap it in Form1
Me.Close()
End Sub
End Class