Johan Johan - 15 days ago 5
Vb.net Question

Best practice for sharing variables across forms in 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.

Answer

There is no one answer to the question. All the methods you listed should 'work.' Which you should use depends why you want to share the variable. For example:

  1. Say you have a form with a list of records, and the user double-clicks a record, so you want to open a new form to edit the record, and you want to pass the record ID. In this case I would add a constructor method to the second form: Sub New(RecordID as String) 'Add code to load the record here End Sub

  2. Say some of the forms in your application may want to know the database path or something else global like that. For that, I would make the appropriate variable on the parent form into a Public variable (called a Field) and access it as MainForm.FieldName. (Disclaimer: Purists will say you shouldn't rely on the somewhat messy fact that VB.NET automatically instantiates an instance of the form class and lets you refer to it by the form name, and that you should instead get a pointer to the actual instance of the form and store it in your child form and access the parent form like that. Actually, this is like number '2' in your post. But it's not actually necessary if you don't mind programmatical incorrectness.)

  3. Say there is something global in your app, like the time the app was started, so you can tell the user "You've been using the app for 5 hours, go get a life!" These things could be stored in a module. (Or in the application class but that's quite hidden)