Communication Between Two Forms


Overview

The aim of the program is to send a message between different forms. If you have a background in visual basic you will 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.

Lets start with the first problem:

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

public void writeMessage(string
str)
{
this
.textBox1.Text = str;
}



in the main form (called frmMain.cs) when I click the button:

private void button1_Click(object sender, System.EventArgs e)
{
me.writeMessage("hello from main");
me.Show();
}



Now lets 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.cs:

public delegate void Message(string str);
public event Message OnMessage;

we need to create a function to send the message
in the frmMain.cs:

private void txtMessage(string str)
{
this.textBox1.Text = str;
}

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

private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(112, 144);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(112, 96);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 1;
this.textBox1.Text = "textBox1";
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.AddRange(new System.Windows.Forms.Control[] this.textBox1,this.button1});
{

this.Name = "frmMain";
this.Text = "Form1";
this.ResumeLayout(false);
me.OnMessage +=
new frmNext.Message(this.txtMessage);
}

and finally we need to use the event in the frmNext.cs int button1_click event:

private void button1_Click(object sender, System.EventArgs e)
{
this.OnMessage("Hello");
}



dont forget you need to hide the frmNext form when youre closing the form otherwise, if you close the form and then try to call it again youll have an error.

So put this code in the form_closing event:

private void frmNext_Closing(object sender,System.ComponentModel.CancelEventArgs e)
{
e.Cancel =
true;
this.Hide();
}

Up Next
    Ebook Download
    View all
    Learn
    View all