none
How to call a function from another form

    Question

  •  

    Hello, I am using VS 2003.   I have two forms. On form #1 I have a simple function that loads a datagrid, the function is called this:

    public void loadDataGrid()
      {
      //Code in here
      }

    On form #2, after the user presses a button, I want to call the function from form #1; however when I type the form name or even namespace.formname.  My function does not appear in the list with the other items.

    namespace.formname.[function does not appear]

    The only way I was able to get it to appear was to rename it

    public static vod loadDataGrid()   but that doesn't work for me because I have variables and other items that it can no longer recognize. 

    Does anyone know how to get around this problem?

    Thanks,
    ~zero

    Tuesday, April 18, 2006 4:07 PM

All replies

  • It is not a problem, it is by design.  You can not reference a type's member unless it is static.  You must use an instance variable to reference instance methods. 

    To resolve your issue you have several options.  Option 1 is to expose a static method that returns a reference to your form's instance on which you can then call the instance method.  This is common in singleton classes but limits you to a single instance of your class.  Option 2 is to somehow pass a reference to your form instance to your second form and then have the second form cache the instance for later use.  This is often done when there is a parent/child relationship.  Option 3 (perhaps the best option in most cases) is to refactor your code such that the common function is stored and accessible through an external class or instance that both forms can access.  This is normally done for things like database access and whatnot.

    For your case you'll need to determine what works best.  Are you guaranteed that the first form will always be open when the second form is?  If the first form can only be open once then a static method to get access to the current instance would work.  In the Form base class is a property called ActiveForm which gives you access to the main form for the application.  A similar approach works in your case as well.  If the function needs to interact with data on the form then you have no choice but to use an instance method in the class.  If the first form is a parent of the second form then you can typecast the Parent property of the form to your first form's type and then use the instance directly like so.

    //In second form
    {
       MyFirstForm frm1 = Parent as MyFirstForm;
       if (frm1 != null)
       {
          ...
       };
    }

    Note above that the code doesn't assume the parent is a valid instance.  Hope this helps.

    Michael Taylor - 4/18/06

    Tuesday, April 18, 2006 6:18 PM
    Moderator
  • Thank you; I appreciate your valuable information!
    Tuesday, April 18, 2006 6:25 PM