Pass values between Windows Forms

In my tutorial “How to Pass Value from One Form to another Form” I discussed how the other form received a value by using a Public Variable.

There are so many discussions on the Internet that argues whether Public Variable is a good programming practice compare to Property. Well, IMHO public variable is an option for simplicity. You do not need to waste line of code just to get the same result.

However, there are some certain areas that we need to consider like OOP and Security. Public Variables as the name implies is subject to vulnerabilities. Arjay_nacion has also commented to my tutorial which breaks the encapsulation principle of OOP.

Without further ado let’s get on the code.

Add two forms in your project called “Form1” and “Form2”. Add the necessary controls as shown in the following screenshot.

[inline:Pass_Value.jpg=Pass values between Windows Forms]

In Form1 add the following code:

  1.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         Dim Frm2 As Form2
  3.  
  4.         Frm2 = New Form2
  5.  
  6.         Frm2.GetFolioNumber = txtFolioNumber.Text
  7.  
  8.         Frm2.Show()
  9.     End Sub

In Form2 add the following code:

  1.     Dim FolioNumber As String
  2.  
  3.     Public WriteOnly Property GetFolioNumber()
  4.         Set(ByVal value)
  5.             FolioNumber = value
  6.         End Set
  7.     End Property
  8.  
  9.     Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  10.         txtFolioNumber.Text = FolioNumber
  11.     End Sub

I hope this helps.

Comments

Hello, good day.. hope you can help me.. i need badly an idea about a dental records a patients record.. in visual basic and it records in Access.. thank i'll appreciate if you could help me.. thank you so much.. my e mail is [email protected]

Add new comment