65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Mar 6, 2013

CPOL
viewsIcon

10685

downloadIcon

314

This tip shows how to share data between two or more forms in a Winforms application.

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:

//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