VB.NET WinForms:
Ensuring a Form Is Already Open Before Access
🔍 Overview
When building VB.NET WinForms applications with multiple windows, it’s common to need access to another form’s data or controls. If you attempt to reference a form that isn’t open (or has been disposed), your app will throw exceptions. In this tutorial, you’ll learn two reliable patterns to check for—and ensure—a form is already open before you use it.
⚠️ The Problem
Imagine you have a secondary settings form (FormSettings
) and from your main form you want to read a value typed there. If FormSettings
isn’t open you’ll get a NullReferenceException
or an ObjectDisposedException
. You must guard against that.
✅ Solution #1: Using Application.OpenForms
' In MainForm.vb
Private Sub BtnReadSettings_Click(sender As Object, e As EventArgs) Handles BtnReadSettings.Click
Dim settingsForm = Application.OpenForms().OfType(Of FormSettings)().FirstOrDefault()
If settingsForm Is Nothing Then
MessageBox.Show("Settings form isn't open. Opening it now...")
settingsForm = New FormSettings()
settingsForm.Show()
End If
' Now safe to access SettingsForm controls
Dim userValue As String = settingsForm.TxtUserSetting.Text
MessageBox.Show("User entered: " & userValue)
End Sub
✅ Solution #2: Singleton Pattern for a Single Instance Form
' In FormSettings.vb
Public Class FormSettings
Private Shared _instance As FormSettings
Public Shared ReadOnly Property Instance As FormSettings
Get
If _instance Is Nothing OrElse _instance.IsDisposed Then
_instance = New FormSettings()
End If
Return _instance
End Get
End Property
Private Sub FormSettings_FormClosed(sender As Object, e As FormClosedEventArgs) _
Handles MyBase.FormClosed
_instance = Nothing
End Sub
End Class
' In MainForm.vb
Private Sub BtnOpenSettings_Click(sender As Object, e As EventArgs) Handles BtnOpenSettings.Click
FormSettings.Instance.Show()
FormSettings.Instance.Focus()
End Sub
🧾 Explanation
- Application.OpenForms scans all currently open forms for the target type.
- Singleton Pattern ensures exactly one instance of
FormSettings
exists, recreating it if closed or disposed. - Both methods prevent errors from referencing a non-existent or disposed form.
💡 Pro Tips
- Always check
IsDisposed
in your singleton getter to handle users closing the form. - Use
BringToFront()
orFocus()
afterShow()
to ensure the form is visible. - For thread-safe scenarios, consider marshaling form access onto the UI thread via
Invoke()
orBeginInvoke()
.
🚀 Use Cases
- Centralized settings windows
- Reusable child dialogs (e.g., About, Help)
- Cross-form data validation in multi-window apps
♥ Here are some online Visual Basic lessons and courses:
No comments:
Post a Comment