User control usage usually requires developing communication between parent form and a user control. Accessing user controls can be easily done through their properties and methods. Calling parent form functions from a user control is not so trivial. The sample below shows how to raise parent form event and call parent form function from within the user control.
The Button inside the User Control raises the Button OnClick event on the form and typing inside the User Control TextBox replicates the text inside the Form’s TextBox. The code seems self descriptive.
Parent form code:
public Form1()
{
InitializeComponent();
formControlPointer += new controlcall(btnHello_Click);
ucMyControl.userControlPointer = formControlPointer;
formFunctionPointer += new functioncall(Replicate);
ucMyControl.userFunctionPointer = formFunctionPointer;
}
public delegate void controlcall(object sender, EventArgs e);
public delegate void functioncall(string message);
private event controlcall formControlPointer;
private event functioncall formFunctionPointer;
private void btnHello_Click(object sender, EventArgs e)
{
MessageBox.Show("You typed: " + txtMessage.Text);
}
private void Replicate(string message)
{
txtReplicate.Text = message;
}
User control code:
public UserControl1()
{
InitializeComponent();
}
public Delegate userControlPointer;
public Delegate userFunctionPointer;
private void btnHello_Click(object sender, EventArgs e)
{
object[] arr = { null, null };
userControlPointer.DynamicInvoke(arr);
}
private void txtUserControl_TextChanged(object sender, EventArgs e)
{
userFunctionPointer.DynamicInvoke(txtUserControl.Text);
}