Hatem
Hatem

Reputation: 589

How to access parent form functions?

Am trying to access the parent form functions (methods). Even by using static keyword it is not working.

The parent form is of type (MDI) and has normal child form. This is C# Application. Am trying use this way to access the methods , but no advance !

this.MdiParent

Please help me !

Upvotes: 1

Views: 6407

Answers (5)

D Stanley
D Stanley

Reputation: 152491

You need to set the MdiParent property of the form when you create it:

// Make the new form a child form.
child.MdiParent = this;
// Display the child form.
child.Show();

Then you can access the parent form. If you just want Form properties you don;t need to cast:

Form parent = this.MdIParent;
string parentTitle = parent.Text;

If you need to access cusotm properties/methoids just cast it to the right type:

ParentForm parent = this.MdIParent as ParentForm;   // using your own type name of course
string title = parent.MyStringProperty;

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39888

Static methods can be accessed by using Type.Method().

If you want to accesse an instance method you need to cast the MdiParent to the correct type.

MyParentType parent = (MyParentType)this.MdiParent;
parent.SomeMethod();

Upvotes: 0

Justin Harvey
Justin Harvey

Reputation: 14672

this.MdiParent returns the instance of type Form

This means it will only show functions that are definedin the Form class definition.

In order to reach other methods, you need to cast it to the class type that implaments the Form, e.g.

((MyForm)Form).MyFunction()

Upvotes: 0

sloth
sloth

Reputation: 101032

You'll have to cast this.MdiParent to the right type.

If your parent form is of type MyForm, use

 ((MyForm)this.MdiParent).MyMethod();

Same for static methods: Call them through the right type

MyForm.MyStaticMethod();

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

If you declared static methods, then you should call them via parent form's class name:

YourParentFormType.YourStaticMethod();

If you want to use instance methods, then you should declare them as public and call via casting MDI parent reference:

((YourParentFormType)this.MdiParent).YourInstanceMethod();

Upvotes: 11

Related Questions