0
votes

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.

2
are you getting get_CurrentClamp not found?user4093832
You're casting to the standard Form type, which of course doesn't have a method called get_CurrentClamp(). You could use Reflection to get the method and invoke it. A better solution would be to make all your child forms implement an Interface that includes that method; then you can cast to the Interface and call the method...Idle_Mind
@MarkHall , i have added the error message to the questionindago
Your error message confirms what everyone already knew. See my comment. Are you going to solve with Reflection or an Interface? Edit with details if you get stuck on the implementation...Idle_Mind

2 Answers

0
votes

If you're sure the active form will be one of the frmDashboard instances, you can declare f to be of that type:

frmDashboard f = this.ActiveMdiChild;

You might want a try/catch around this just in case. (Works in VB, anyway. Not sure about C#.)

0
votes

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