Sending information between two Windows Froms in C#
This might be a novice question. :). Consider the following scenario.
- Suppose we have two windows forms that are already "loaded" (i.e You can see both the forms)
- Form 1 contains a textbox and a "submit" button while the form 2 contains a text lable.
- The user can enter a string in the textbox and press submit on form 1 The lable on form 2 should be updated with the new text.
What is the best way to achive this? An开发者_运维知识库y formal way to do this? I don't want to increase the variable scopes unnecessarily.
Edit : Both the forms belong to same application
Assuming these forms are part of the same application, you need to have a common data model where you keep your data and then your forms "bind" to this data model. Check out M-V-C or M-V-VM patterns. This would also nicely separate your UI from your data.
Do some research on model view controller pattern and databinding in winforms.
Create a seperate controller class and reference this in the two forms, which implements INotifyPropertyChanged
. On the controller, have a property which propagates the changed events from and to the forms.
Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.
With this approach you can do communication in different ways.
Download Link for Sample Project
//Your Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
public string LabelText
{
get { return Lbl.Text; }
set { Lbl.Text = value; }
}
}
//Your Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = txtMessage.Text;
}
}
alt text http://ruchitsurati.net/files/frm1.png
alt text http://ruchitsurati.net/files/frm2.png
精彩评论