Call public parent function from child class

c#, parent-child

Solution

You'll have to have an instance of the `Main` form in your `UpdateDialog` form. As you say that UpdateDialog is a child form of your Main form, I guess that you create the UpdateDialog in your Main form and do a show there. Before showing that form, you could assign the `Parent` property.

var updateDialog = new UpdateDialog();
// Or use "UpdateDialog updateDialog = new UpdateDialog();" as people like Andreas Johansson don't like the "var" keyword
// Do other stuff here as well
updateDialog.Parent = this;
// Or use Show() for non modal window
updateDialog.ShowDialog();

You get the error `ArgumentException: Top-level control cannot be added to a control.`. Now this can be solved in two ways.

- You can set the `TopLevel` property to `false` on your Main form (I'm not a huge fan of this).

- You can use the `Owner` property to your Main form (`this`). Below two ways of doing it.

You can set the `Owner` manually:

updateDialog.Owner = this;

Or you can add `this` as parameter to the `Show(owner)` or `ShowDialog(owner)` methods; this way, the `Owner` is also being set.

updateDialog.Show(this);
// or
updateDialog.ShowDialog(this);

"Full" code makes this:

var updateDialog = new UpdateDialog();
// Do other stuff here as well
updateDialog.Owner= this;
updateDialog.ShowDialog(); // or use .Show()
// or
updateDialog.ShowDialog(this); // or use .Show(this)

Problem

Inside my `Main` method I'm instantiating the `UpdateDialog` class inside which based on if the user presses a button or not I need to call `function1()` from `Main`. Here is the code: ``` public partial class Main : Form { public void function1() { doing_stuff_here(); } private void button1_Click(Object sender, EventArgs e) { var update = new UpdateDialog(); update.ShowDialog(); } } public partial class UpdateDialog : Form { private void button2_Click(object sender, EventArgs e) { //call here function1() from Main } } ``` What should I do to be able to call `function1()` from `Main` inside the partial class `UpdateDialog`? LE: although the method suggested by Styxxy seems right it doesn't work well in my app because of `cross-thread invalid operation` so I ended up using the `delegate workaround` suggested by Cuong Le.

Original source