slao
slao

Reputation: 2086

Sending button event to object host class

I have a windows form called FormMain in ClientForms project. Now this(FormMain) form opens another form called FormScheduler in Scheduling project.

Now, I want to send a message back to FormMain when a button_click method event is triggered in FormScheduler.

My solution creates a circular dependency. Is there another way, like using delegates ?

Upvotes: 0

Views: 54

Answers (1)

Jay Riggs
Jay Riggs

Reputation: 53593

Use events.

In your form FormScheduer add a button and the following code:

public event EventHandler ButtonClicked;

private void button1_Click(object sender, EventArgs e) {
    if (ButtonClicked != null) {
        ButtonClicked(this, EventArgs.Empty);
    }
}

In your FormMain, instantiate and display your FormScheduer form like this:

var form = new FormScheduer();
// Listen for the ButtonClicked event...
form.ButtonClicked += form__ButtonClicked;
form.Show();

Your form_ButtonClicked method on FormMain will be called when the button on FormScheduler is clicked:

void form__ButtonClicked(object sender, EventArgs e) {
    Console.WriteLine("clicked");
}

Upvotes: 1

Related Questions