Click here to Skip to main content
15,891,136 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
6 Mar 2013CPOL 10.4K   306   6   2
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)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGood Trick!! Pin
JayantaChatterjee7-Mar-13 4:56
professionalJayantaChatterjee7-Mar-13 4:56 
GeneralRe: Good Trick!! Pin
zheng shuo7-Mar-13 21:47
zheng shuo7-Mar-13 21:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.