declare global variables in VB.NET

boig used Ask the Experts™
I need to use a variable in some forms, but don't know how to delcare it to be public,global,shared...

   Dim doc As XmlDocument = New XmlDocument()

any help?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

There are a couple of options.

Here's one:
Create a module in which you declare the XmlDocument.

Another one:
Create a class in which you create a shared instance. This will make it always accessible.

There are some other options but to choose the best option means to know the design of your application and your current structure (and where it is used etc.)


I have "Form1" where you choose an option from a "ListBox"(generated from XML); then "Form2" is opened where you must be able to modify data from the "XmlDocument"; finally you must be able to write to a file the "XmlDocument" when you return to "Form1"

Just write

Shared doc as XmlDocument

and declare it with
doc = New XmlDocument()
when you are populating the XML document (thus before modifying). Write the shared statement in a place where you can always access it... for example in a class which does the transformations. I would NOT put it in the Form1 or other forms. place it at least in a new class (and namespace if you use those). then access 'm like:


I have created a new class, but it the debbuger give me "Declaration expected" and underlines doc:

Imports System.Xml
Imports System.IO

Public Class docuXML
    Shared doc As XmlDocument
    doc = New XmlDocument()       'doc goes underlined
End Class
Like i said, you should place the creation in a function.

Public Class Class1
    Shared doc As Xml.XmlDocument

    Public Sub Create()
        doc = New Xml.XmlDocument()
    End Sub
End Class

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial