Hi All

Does Anyone know how to make a variable public to all forms within the application.

Eg Public MyPath = "C:\" can do for one form but not all

Dani AI

Generated

As pointed out, a public field on a Form can be referenced from other Forms and 's Module suggestion is the usual quick fix. Both work for small one-off utilities. For anything that may grow, scattering mutable globals across UI classes makes maintenance, testing and threading harder.

A more robust option is to store application values in settings (Project > Properties > Settings). Settings provide typed storage and two scopes: Application (read-only at runtime) and User (persistable per user). Example access in VB:

Dim basePath As String = My.Settings.DefaultPath
My.Settings.DefaultPath = "C:\SomeFolder"
My.Settings.Save()

Microsoft guidance on application settings is here: .

For runtime-only shared state, prefer a small sealed class with Shared properties instead of a Module; it gives a clearer API surface and is easier to refactor or wrap for testing:

Public NotInheritable Class AppState
    Private Sub New() End Sub
    Public Shared Property CurrentPath As String
End Class

Practical tips: avoid hard-coding roots like "C:\" — use Environment.SpecialFolder and construct paths with IO.Path.Combine to avoid double-slashes and platform issues. Always validate existence and permissions (IO.Directory.Exists, try/catch on IO operations). If multiple threads will read/write the value, guard writes with SyncLock. For strictly read-only configuration, app.config/ConfigurationManager.AppSettings is also an option. See Path.Combine docs for safe path construction: System.IO.Path.Combine.

Recommended Answers

All 3 Replies

If your Public declaration is on Form1, then call it like: [B]Form1.MyPath[/B] from any other Form.

Also, always set a Declaration Type when declaring something. In this case, "String" = Type.

Public MyPath As String = "C:\"
Member Avatar for Member #857553

Another thing you could do is add a module to the project.

Module FilePathData
    Public MyPath as String = "C:\"
    'Some other stuff
End Module

Thanks to you both for the ideas.

I will take them onboard and use them.

codeorder - thank you once aagin for the help, the advice you give is always simple and to the point.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.