Passing Data between Windows Forms
Sometimes people can have a pretty tough time finding a thorough guideline as to how they can achieve passing data between Windows Forms (namely from a parent form to a child form). Since it’s far simpler than it would seem at first glance, I figured I’d walk through it real quick.
I’ve setup a Windows Forms Application project called Demo.
It consists of two forms, MainForm.cs, and DisplayForm.cs.
MainForm has a multi-line textbox control and a “Display” button. DisplayForm has a multi-line read-only textbox control and a “Close” button. Our goal will be to type text into the textbox on MainForm, click the Display button, and have DisplayForm launch and display the message we typed in the read-only textbox, after which we will be able to click “Close” in order to close DisplayForm.
First thing’s first. DisplayForm needs to know what MainForm is, therefore we must assign a variable to MainForm within our DisplayForm partial class.
In DisplayForm.cs, you should see the following:
namespace Demo
{
public partial class DisplayForm : Form
{
public DisplayForm()
{
InitializeComponent();
}
}
}
Modify the above code so that you have the following:
namespace Demo
{
public partial class DisplayForm : Form
{
private MainForm _main;
public DisplayForm(MainForm form)
{
InitializeComponent();
_main = form;
}
}
}
In MainForm’s design view, double-click on the display button. Visual C# will create a method for the Click event of that button control. Although your control or method may have a different name, make sure that the two lines within the method are similar to those shown below:
private void buttonDisplay_Click(object sender, EventArgs e)
{
DisplayForm form = new DisplayForm(this);
form.Show();
}
Now DisplayForm will be aware of MainForm and will be able to reference MainForm’s public, protected internal, or internal controls.
Next, let’s make sure that textBoxMessage (the multi-line textbox control on our MainForm) has its Modifier set to Protected Internal, which you can adjust by editing the control’s properties.
Now we’re ready to reference that control from within DisplayForm.
I simply created a method called DisplayMessage() which sets the display textbox control to show the message from the message textbox control on MainForm, as shown below. Then I call the method from within the public DisplayForm() method:
namespace Demo
{
public partial class DisplayForm : Form
{
private MainForm _main;
public DisplayForm(MainForm form)
{
InitializeComponent();
_main = form;
DisplayMessage();
}
private void DisplayMessage()
{
textBoxDisplay.Text = _main.textBoxMessage.Text;
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Now you may compile/debug your application and test it. Below is a screenshot of my final result.
