Hi Failure,
|| I know it's best to use objects instead of pulling info
|| directly from a control, ...
A control <is> an object, so no problem there.
|| It seems to me that if I create a textbox on Form1 and
|| make it Public, I should then be able to put a label on
|| Form2 and make it display the contents of the textbox
Yep.
|| by putting code like this in Form 2's load event:
|| label.text = form1.textbox.text
Ah. Now that <doesn't> work, as you've found. And it gives the cryptic
message "Reference to a non-shared member requires an object reference." So
what does it mean?
You declare Form1 like so:
Public Class Form1 : Inherits System.Windows.Forms.Form
Looking at it literally it says create a <Class> called Form1. It doesn't
say create a Form called Form1. In fact the Form is created additionally
<from> the Class but this is behind the scenes. [It's easier to understand if
you do C# because there, you must create the initial form yourself.]
If you use the name Form1 in your code, you are still talking about the
Class. There <is> no Form called Form1. This is all very different to earlier
VBs, so it's no surprise that it's confusing.
|| How *would* I directly grab the text value from Form1's
|| textbox, without using an object?
You <have> to use an object. The nameless Form created as an instance of
Class Form1 <is> an object.
What you do is tell your second Form who your first is. In other words you
give it an obect reference.
Here's some code.
In Class Form1:
Private Sub Form1_Load(...) Handles MyBase.Load
1 Dim Form2 As New Form2 (Me)
Form2.Show
End Sub
In line 1 it says create an instance of Form2 and assign it to an object
variable called Form2. This is allowed but <very bad practice>. Don't do it.
It can cause untold confusion.
Here's some better code.
In Class Form1:
Private Sub Form1_Load(...) Handles MyBase.Load
1 Dim MyForm2 As New Form2 (Me)
2 MyForm2.Show
End Sub
And In Class Form2:
3 Public Sub New (FirstForm As Form1)
4 Me.New()
5 Label1.Text = FirstForm.TextBox1.Text
End Sub
In line 1 the first Form creates an instance of Form2 and passes itself to
the new Form.
In line 2 it shows the new Form.
Line 3 declares a constructor for objects of Class Form2 which takes
another Form as a parameter.
In line 4, it calls the <other> constructor for Class Form2 as this
actually sets everything up. Forget this and you'll get an error on line 5.
(Try it.) [The other option would be to copy the contents of New() into this
constructor, but it's easier and less error-prone to simply call it.]
Line 5 gets the text from the first Form's TextBox, as you wanted.
As you can see, an object reference is required to do the job. And MyForm2
won't know about the first Form until it's told.
All the best,
Fergus