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:
Form1 frm = new Form1(); // Creating object of parent to access shared variable
frm.a = "abc"; // Passing value
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:
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
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.)
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)