Search code examples
c#winformsmdimdichild

How do I call a method of a child form from mdi parent c#


I have several child forms but they have one common methods in them, get_CurrentClamp(). i want to call the method of the current active mdichild from the MDI parent.

This is the onclick event of a menuitem in the MDIparent form MDIMain.cs that should call the method.

....
 private void mnugetCToolStripMenuItem_Click(object sender, EventArgs e)
   {
    if (MdiChildren.Any())
            {
                Form f = this.ActiveMdiChild;            
               f.get_CurrentClamp(varCurrentThreshhold);
            }
   }
.....

In the child form frmDashboard.cs

public void get_CurrentClamp(float curThreshhold=5.5)
        {
           ...
        }

But i keep getting an error, any where am going wrong? Any help will be greatly appreciated!

the error a getting is this

Error 3 'System.Windows.Forms.Form' does not contain a definition for 'get_CurrentClamp' and no extension method 'get_CurrentClamp' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?)

Thats the error am getting on the mdiparent form.


Solution

  • Thanks to Idle_Mind i solved the problem by using an Interface. i created a new interface in a file called IChildMethods.cs and below is the interface

     internal interface IChildMethods
        {
            void get_CurrentClamp(float curThreshhold=5.5);
        }
    

    and on the child forms i just included the interface like below on the form frmDashboard.cs;

     public partial class frmDashboard : Form, IChildMethods
    

    and on the mdiform MDIMain.cs

    ....
     private void mnugetCToolStripMenuItem_Click(object sender, EventArgs e)
       {
        if (MdiChildren.Any())
                {
                   if (this.ActiveMdiChild is IChildMethods)
                {
                    ((IChildMethods)this.ActiveMdiChild).get_CurrentClamp(varCurrentThreshhold);
                }            
    
                }
       }
    .....
    

    I havent tried using the Reflection method since the Interface method worked, but am just wondering if Reflection is better than using an Interface in such a problem