Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for sharing variables across forms in VB.NET

Tags:

vb.net

I need to share variables across two forms in VB.NET. One of them is the main form and the other is a child form.

I have been searching, and I have found a few methods. I want to use the best method to do this. I have listed a few options below. Please comment on which one would be the best option:

  1. Create a static/shared variable in one of the forms and access it in the other forms via:

    Form1 frm = new Form1(); // Creating object of parent to access shared variable
    frm.a = "abc"; // Passing value
    
  2. Send an instance of the main form to the child form when creating the child form. The variables can then be accessed via a property function.

  3. Create global variables in a module. This seems like the easiest option, but I doubt it is the best option.

  4. I also read something about delegates and events, but I don't know how to implement this.

If there is another method I haven't mentioned, please share it with me.

like image 735
Kritz Avatar asked Oct 31 '25 17:10

Kritz


1 Answers

Create two forms. Add 3 radio buttons and 1 button to form1. Add a label to form2. In the code for form1 type

    Public rdb As Integer = 1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
     Form2.Show()
If RadioButton1.Checked Then
            rdb = 1
        ElseIf RadioButton2.Checked Then
            rdb = 2
        ElseIf RadioButton3.Checked Then
            rdb = 3
        End If
End Sub

Then in form2's code

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Label1.Text = Form1.rdb
    End Sub
like image 136
josiahg Avatar answered Nov 04 '25 09:11

josiahg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!