Best practice for sharing variables across forms in VB.NET

后端 未结 6 1541
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 05:56

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 metho

6条回答
  •  Happy的楠姐
    2021-01-07 06:14

    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)

提交回复
热议问题