Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Windows Form Method from its User Control

Tags:

c#

.net

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

like image 736
BreakHead Avatar asked Jun 02 '11 07:06

BreakHead


People also ask

How do I call a Windows Forms control from another thread?

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.

How to retrieve the form that the control is on?

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.

How to use user control in Salesforce forms?

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.

Should I put code on the form or user control?

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.


1 Answers

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);
    }
like image 72
BreakHead Avatar answered Sep 30 '22 18:09

BreakHead