I know it's best to use objects instead of pulling info directly from a control, but just for my understanding, please help me figure this out:
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 by putting code like this in Form 2's load event:
label.text = form1.textbox.text
But it doesn't work. So, minor syntax issues aside, what am I not understanding? How *would* I directly grab the text value from Form 1's textbox, without using an object?
ANSWER
I know it's best to use objects instead of pulling info directly from a control, ...
A control
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
If you use the name Form1 in your code, you are still talking about the Class. There
How *would* I directly grab the text value from Form1's textbox, without using an object?
You
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
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
(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...
/www.byte.om/forum/
0 comments:
Post a Comment