disasterkid
disasterkid

Reputation: 7278

Best way for user controls to communicate within the form

I had a full paragraph of moaning which is now removed. So I cut to the chase:

  1. How can I notify userControlA that a button has been clicked in userControlB?
  2. How can I notify the main form that a button has been clicked in userControlA?

Is the answer provided in this post the best solution? I'm looking for the best solution.

Upvotes: 3

Views: 211

Answers (1)

Sinatr
Sinatr

Reputation: 22008

An example

public partial class UserControlA
{

    // method to inform
    public void DoSomething(string text)
    {
        ... // do something with text
    }
}

public partial class UserControlB
{
    public event Action SomethingChanged;
    public string SomeText {get; set;} // some property

    private void button1Clicked(object sender, EventArgs e)
    {
        if(SomethingChanged != null)
            SomethingChanged(); 
    }
}

// in form contructor (for demonstration purpose)
var a = new UserControlA();
var b = new UserControlB();
this.Controls.Add(a);
this.Controls.Add(b);
var handler = () => a.DoSomething(b.SomeText);
b.SomethingChanged += handler;

Now, when you click button1 in UserControlB, then UserControlA get its DoSomething() method called. Form is used to pass event, but you can subscribe to event in UserControlA directly, you will need to pass instance of UserControlB somehow (property, method, constructor).

Upvotes: 1

Related Questions