Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling parent form functions from a user control

0.00/5 (No votes)
22 Apr 2008 2  
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.

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); 
} 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here