NDraskovic
NDraskovic

Reputation: 706

Triggering method(s) in parent forms from a child form

I have a problem with triggering a method in various parent forms from one child form. This child form is used to take user input and pass it to the parent form. Since this input is identical for various types of work (each type is realised in it's own form), I call this child form from various forms.

So far I've solved this problem like this:

In child form there is a piece of code:

private void button3_Click(object sender, EventArgs e)
{            
    if (Parent.GetType() == typeof(MyType))
    {
        if ((Parent as MyType).MyFunction()))
        {
            this.Close();
        }
    }

}

Parent is a property of type object. This child form is called from a parent form with this code:

MyChildForm IPU = new MyChildForm();
IPU.Parent = this;            
IPU.ShowDialog();

The problem with this approach is that I might end up with tens of if-else blocks, one for each type of parent form that need's this child form for input. My question is - is there a way to shorten this code, so that it work's for every type that has a function named MyFunction?

I've tried something like this:

(Parent as typeof(Parent.GetType())).MyFunction()

But I get an error 'Parent is a property but is used like a type'

Upvotes: 1

Views: 122

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can create interface

public interface IParent
{
    bool MyFunction();
}

And make Parent property of type IParent. Then make your parent forms implement this interface. Usage will look like:

private void button3_Click(object sender, EventArgs e)
{            
    if (Parent.MyFunction())        
        this.Close();
}

Upvotes: 2

Related Questions