declare global variables in VB.NET

boig
boig used Ask the Experts™
on
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?
thanks.
Comment
Watch Question

Do more with

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

Commented:
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.)

Author

Commented:
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"

Commented:
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:
ClassName.doc

Author

Commented:
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
-----------------------------
Commented:
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