Old VB6 Dog, New .Net Tricks

BridgeGuy
12-31-2003, 10:14 AM
I am a old VB6 programmer trying to learn VB.Net.

Under VB6, when referencing a control on another form, the only code needed to reference TextBox1 control on Form1 from the Click Eevent of Form2, would be following;


Form1.TextBox1.Text = "Test"

Now for my problem.

I tried a sample VB.Net application that has two forms, Form1 and Form2, each with a TextBox1 control. Form1 is designated as the project Startup Form. In Form1's Public Class module, I placed the declaration;

Public Form2 as New Form2

In Form1's Click event I placed the following code to Show Form2 and place the message "Test" in TextBox1.

Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click

Form2.TextBox1.Text = "Test"
Form2.Show()

End Sub

In Form2's Click Event I placed the following Code in an attempt to change the text in TextBox1 on Form1.

Private Sub Form2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click

Dim frm As Form1
frm.TextBox1.Text = "It worked"

End Sub

When I run this code I get the following error;

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe

Additional information: Object reference not set to an instance of an object.

My question is this, how do I get an Object Reference to Form1?

Any help would be appreciated.

Thanks,

Jim

VBJoe
12-31-2003, 11:11 AM
The error means you haven't instantiated an object. Try declaring frm using the New keyword.

reboot
12-31-2003, 11:47 AM
If you Dim it as New, it isn't the same object, so the textbox will never get set. That does get rid of the error though. :)

Here's an article explaining WHY this VB6 concept no longer works in .Net.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchWorkingWithMultipleFormsInVisualBasicNETUpgradingToNET.asp

As far as a solution, the most common way of handling this is to simply pass the first form to the constructor in the second form

'showing form2 from form1
Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click
Dim frm As New Form2(Me) 'pass this form
frm.TextBox1.Text = "Test"
frm.Show()
End Sub
'constructor code for form2
Private _frm As Form1

Public Sub New(ByVal frm As Form1)
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

_frm = frm

End Sub
'set the textbox on form1 from form2
Private Sub Form2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click

_frm.Textbox1.Text = "It worked"

End Sub

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum