Communicating between two Forms in VB.NET

Overview

The aim of the program is to send a message between different forms. If you have a background in visual basic you'll find it quite difficult because even if you make the objects public, when you try to send messages from one form to another it will have no effect. 

Description

We have to distinguish between two different situations.

  1. The form isn't open yet.
  2. The form is already open.

The first case is easier than the second one, because you only need to make the object in the second form public (better if you make a public function) and use it before using the show() method.

In the second case you need to use delegation.

Let's start with the first problem:

In the second form (called frmNext.cs) I made a public function to write something in the textBox1:

Public Sub writeMessage(str As String)
Me.textBox1.Text = str
End Sub 'writeMessage

1.jpg

In the main form (called frmMain.vb) when I click the button:

Private Sub button1_Click(sender As Object, e As System.EventArgs)me.writeMessage("hello from main")
me.Show()
End Sub 'button1_Click

2.jpg

Now let's look at the second problem - sending a message to the first form. First we need to declare the delegate and the event in the frmNext.vb:

Delegate Sub Message(str As String)
Event OnMessage As Message '

Message in the frmMain.vb:

Private Sub txtMessage(str As String)
Me.textBox1.Text = str
End Sub 'txtMessage

Then we need to set the reference of the event in the frmNext.cs:
 

Private Sub InitializeComponent()
Me.button1 = New System.Windows.Forms.Button()
Me.textBox1 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
' button1
'
Me.button1.Location = New System.Drawing.Point(112, 144)
Me.button1.Name = "button1"
Me.button1.TabIndex = 0
Me.button1.Text = "button1"
Me.button1.Click += New System.EventHandler(Me.button1_Click)
'
' textBox1
'
Me.textBox1.Location = New System.Drawing.Point(112, 96)
Me.textBox1.Name = "textBox1"
Me.textBox1.TabIndex = 1
Me.textBox1.Text = "textBox1"
'
' frmMain
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.textBox1, Me.button1})
Me.Name = "frmMain"
Me.Text = "Form1"
Me.ResumeLayout(False)
me.OnMessage += New frmNext.Message(Me.txtMessage)
End Sub 'InitializeComponentand finally we need to use the event in the frmNext.cs int button1_click event:
Private Sub button1_Click(sender As Object, e As System.EventArgs)Me.OnMessage("Hello")
End Sub 'button1_Click

4.jpg

Don't forget you need to hide the frmNext form when you're closing the form otherwise, if you close the form and then try to call it again you'll have an error.

So put this code in the form_closing event:

Private Sub frmNext_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs)
e.Cancel = True
Me
.Hide()
End Sub 'frmNext_Closing


Similar Articles