I have a User Control on My windows Form, and there is a button on my user control on click of which I want to call its form method.
Thanx
There are two ways to safely call a Windows Forms control from a thread that didn't create that control. Use the System.Windows.Forms.Control.Invoke method to call a delegate created in the main thread, which in turn calls the control.
If you only need to call methods provided by the Form interface you can simply call FindForm to retrieve the form that the control is on. MyForm form = (MyForm)this.FindForm (); form.DoSomething (); Excellent. Very simple solution. Show activity on this post.
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.
Rethink your approach. If there is a cross-cutting conern that is shared by both the user control and the form, don't put the code for it on the form. By nature the user control can be shared across multiple forms, and there is no good reason why the user control should be tightly coupled to a specific form.
What worked for me is using delegate
public delegate void ClickMe (string message);
public partial class CustomControl : UserControl
{
public event ClickMe CustomControlClickMe;
public CustomControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (CustomControlClickMe != null)
CustomControlClickMe("Hello");
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
customControl1.CustomControlClickMe += new ClickMe(button2_Click);
}
void button2_Click(string message)
{
MessageBox.Show(message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With