Sharing Functions and constants between forms in an application

I'm sure this is a really easy thing to do but I cannot get it to work.

I have declared functions and constants as public in my main form but these cannot be seen by other forms in the application. Could  there be something simple I'm missing as everywhere I've searched just states - if the objects are delared public then they will be available for use in other forms  

 

All help appreciated.



Answer this question

Sharing Functions and constants between forms in an application

  • Mansoor Adnan Ali

    Was the class also marked a public.


  • arkiboys

    Adding shared didn't help (in fact it won't let me share a constant)

    But moving the declarations and functions into a module made all the difference, they can now all be seen by the child forms (and the main form). Many thanks for your help


  • ruleDWorld

    if you mean the main form class, yes - I think I just about named everything public just in case!
  • fdc2005

    Import the form's namespace.

  • ReneeC

    Apologies but I'm not quite sure what that means - how do I do this and where
  • Arran Siu

    You would have to reference the constant through the form name (as Nobugz demonstrated in the example), for example:

    Form1.FunctionName

    If you don't want to use the reference 'Form1' to everything, you can 'import' the class into another form, class, etc. by putting the following at the top of that module:

    Imports Form1

    You can then reference the function(s) and constants on that form directly.

    (however, I wouldn't do this for a form, unless you are extending the functionality of the form: it would be better to choose a class or module as appropriate for encapsulation purposes).

    If it's not working correctly, you are possibly doing something that we are not aware of.



  • zd84

    Try using the Shared keyword in the function declaration. That way, the other forms won't have to use a reference to your main form to use the functions. For example:

    Public Class Form1
    Public Const pi As Double = 3.14
    Public Shared Function WhoIz() As String
    Return "nobugz"
    End Function
    End Class

    Public Class Test
    Sub Sample()
    Dim d As Double = Form1.pi
    Dim s As String = Form1.WhoIz
    End Sub
    End Class

    Using the constant "pi" generates a warning, that looks like a compiler bug to me. If this is what you want to do, put your declarations in a Module instead of a form.


  • Sharing Functions and constants between forms in an application