Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

How to Share Data between Two or More Forms in Window Forms Application

4.50/5 (2 votes)
6 Mar 2013CPOL 10.6K   308  
This tip shows how to share data between two or more forms in a Winforms application.
Image 1

Introduction

The post explains how to share and exchange data between two or more Forms in Window Forms Application.

Background

When I began to use the C# programming language, I encountered some problems with data share in different Forms. I had tried to use text file, *.ini file and XML file, but as you know, it is inefficient to access the disk frequently. So I attempted other methods. This is why I wrote this post.

Using the Code

The code in this article was developed in C# using Visual Studio 2010 Ultimate.

The main code snippet is as follows:

C#
//in the Fields
FormMainFrame m_formMainFrame; //FormMainFrame is the first form in your application.
 
//often in the Form_Load() method
m_formMainFrame = (FormMainFrame)Application.OpenForms[0];
 
//in the Event
if (m_formMainFrame.Form2 != null)
{
    //the reference of Form2 is a property of FormMainFrame.
    //the reference of LabelTest is a property of Form2.
    MessageBox.Show(m_formMainFrame.Form2.LabelTest.Text); 
}

History

  • 4th March, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)