You can assign events and event handlers just as you like. Here's some example code. There's two forms each with a button and a label. Form2 has a text box that you can enter tesxt in.
When the button on Form2 is clicked it changes the label text and fires an event that is picked up by Form1. The label on Form1 then changes to match that on Form2.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 dlg = new Form2();
dlg.NameChanged += OnNameChanged;
dlg.ShowDialog();
}
private void OnNameChanged(object sender, NameChangeEventArgs args)
{
this.label1.Text=args.NewName;
}
}
public class NameChangeEventArgs : EventArgs
{
public NameChangeEventArgs(string name)
{
this.NewName=name;
}
public string NewName{get;private set;}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
if (this.NameChanged != null)
{
this.NameChanged(this, new NameChangeEventArgs(label1.Text));
}
}
public event EventHandler<NameChangeEventArgs> NameChanged;
}
}
edit - Sorry I didn't read your question correctly.
If you want to avoid this
Form2 dlg = new Form2();
dlg.NameChanged += OnNameChanged;
dlg.ShowDialog();
Then you could change the Form2 constructor to:
public Form2(EventHandler<NameChangeEventArgs> eventhandler)
{
InitializeComponent();
NameChanged += eventhandler;
}
And then you setup and show Form2 as follows:
Form2 dlg = new Form2(OnNameChanged);
dlg.ShowDialog();
Unfortunately there really is now way of avoiding the +=
statement in assigning event handlers as they must be assigned once the parent class has been instantiated.
You could of course instantiate the dialog once and just not show it until required, but then you'll have to cope with the dialog being closed and destroyed, which means not using ShowDialog, but Show instead therefore requiring you to emplace code to ensure that the dialog remains modal.