Wednesday, August 5, 2009

C# Use delegates for Windows Form Communication

Problem:
You have a main form and a secondary form. You want the secondary form to send information to the main form. However, the secondary form does not hold an instance to the main form.

Code for the secondary form:
public delegate void TextBoxDelegate(string strMessage);
public TextBoxDelegate TextBoxCallback;

private void button1_Click(object sender, EventArgs e)
{
TextBoxCallback(txtBoxOnSecondaryForm.Text);
}

Code for the main form:

private void button1_Click(object sender, EventArgs e)
{
Form2 formSecondary = new Form2();
formSecondary.TextBoxCallback = new Form2.TextBoxDelegate(this.WriteToTextBoxInMainForm);
formSecondary.Show();

}

private void WriteToTextBoxInMainForm(string strMessage)
{
this.txtBoxOnMainForm.Text = strMessage;
}

No comments: