C# Accessing MDI Parent methods from MDI Child forms

While in a new project (trying to get my Fluke 289 communicate with my PC), I ran into an interesting C# trickie that I thought it might be interesting to share. Here’s the UseCase: getting to have a parent MDI form and several child forms, you want to run selected parent methods from child forms. In my particular case, the serial port connection routines are all run in the MDI parent class; moreover, some queries are run in the MDI parent class but I need to access these queries (methods) from some child forms. There are two scenarios I ran into:

  • if the method in the parent form is static
  • if the method in the parent form is public

If the method in the parent form is static, these should be called via parent’s form class name (for objective-C aficionados, static methods in C# are like class methods in Objective-C):

MyMDIParentFormClass.myStaticMethod();

This is simple. However, it gets trickier if the method is an instance method. In this case you should declare them as public

public void myStaticMethod();

and call via casting MDI parent reference:

((MyMDIParentFormClass)this.MdiParent).myStaticMethod();

Nice. Hope this helps.
Have a great day.

AP

Filed in C# stuff and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *