Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 14946

VS 2017 Sharing Variable Between Two Forms

$
0
0
Hello,
I am working on sharing a variable between Form1 and Form2. Form1 has a Textbox1 and Button1. Form2 has the same. I have a private shared instant variable called _sharedvartest in my code for Form2 which is populated from a public shared property called sharedVarTest. My code seems to work properly when I am not using a constructor for Form2. However, when I add a constructor on Form2 I seem to lose my Textbox1 and Button 1 and I get an error in my Form2_Load event on Me.TextBox1.Text=sharedVarTest. The error is System.NullReferenceException: 'Object reference not set to an instance of an object.'

Here is my code:

Code:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        'Create 3 new forms named Name1, Name2, Name3
        For i As Integer = 2 To 4

            If i = 2 Then
                TextBox1.Text = "Name1"
            ElseIf i = 3 Then
                TextBox1.Text = "Name2"
            Else
                TextBox1.Text = "Name3"
            End If

            'Name new Forms
            Dim frm As New Form2(TextBox1.Text)
            frm.Name = TextBox1.Text

            'Add Text to new Forms
            Dim strName As String = ""
            strName = String.Concat("frm", CStr(i))
            frm.Text = strName

            'Show Form
            frm.Show()

        Next
     
    End Sub

End Class



Public Class Form2

    Private Shared _sharedvartest As String
   
    '????????????????????????????????????????????
    'Constructor
    Public Sub New(sharedVarTest)
        _sharedvartest = sharedVarTest
    End Sub
    '???????????????????????????????????????????

    Public Shared Property sharedVarTest As String
       
        Get
            Return _sharedvartest
        End Get
               
        Set(value As String)
            _sharedvartest = value
        End Set
               
    End Property

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles
    MyBase.Load

        Me.TextBox1.Text = sharedVarTest  '?????????Errors Here

    End Sub

End Class


Viewing all articles
Browse latest Browse all 14946

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>