This comes up so many times in the Forums/Quick Answers I thought it was time for a Tip that I can point people to.
Passing a value from a child form to the parent is best achieved using an event. To a noob, creating events, especialy when passing a value, can seem unnecessarily complicated. The code below shows a simple implementation that can be adapted as required.
The example is using Forms, but the priciple applies to any object type.
All the code is commented, any questions - just ask!
using System;
public class TextEventArgs : EventArgs
{
private string text;
public TextEventArgs(string text)
{
this.text = text;
}
public string Text
{
get { return text; }
}
}
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Form2 : Form
{
public event EventHandler<TextEventArgs> NewTextChanged;
private string newText;
private TextBox textBox;
public Form2()
{
InitializeComponent();
textBox = new TextBox();
textBox.Location = new Point(92, 122);
textBox.TextChanged += new EventHandler(textBox_TextChanged);
Controls.Add(textBox);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
NewText = textBox.Text;
}
public string NewText
{
get { return newText; }
set
{
if (newText != value)
{
newText = value;
OnNewTextChanged(new TextEventArgs(newText));
}
}
}
protected virtual void OnNewTextChanged(TextEventArgs e)
{
EventHandler<TextEventArgs> eh = NewTextChanged;
if (eh != null)
eh(this, e);
}
}
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
{
private Button buttonShowForm2;
public Form1()
{
InitializeComponent();
buttonShowForm2 = new Button();
buttonShowForm2.Location = new Point(105, 121);
buttonShowForm2.Text = "Show Form2";
buttonShowForm2.Click += new EventHandler(buttonShowForm2_Click);
Controls.Add(buttonShowForm2);
}
private void buttonShowForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.NewTextChanged += new EventHandler<TextEventArgs>(form2_NewTextChanged);
form2.ShowDialog();
form2.NewTextChanged -= form2_NewTextChanged;
form2.Dispose();
form2 = null;
}
private void form2_NewTextChanged(object sender, TextEventArgs e)
{
Text = e.Text;
}
}