Windows Develop Bookmark and Share   
 index > Windows Forms General > Accessing objects of a Form from another Form in VB .net
 

Accessing objects of a Form from another Form in VB .net

Hi, I'm using VB .net 2003 windows form. I have 2 forms.

Form1 contains: TextBox1, ComboBox1

Form2 contains: CommandButton1

I want to use the text entered in TextBox1 and ComBox1 of Form1 in the Form2_Load of Form2. I have used the following code:

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim Form2Obj As New Form2

Dim cFName As String

Dim cDDOB As String

cFName = Form2Obj.TextBox1.Text.ToString

cDDOB = Form2Obj.ComboBox1.Text.ToString

MessageBox.Show(cFName)

End Sub

But this code is not working. It's not printing the cFName. What should be the appropriate code? Do I need to use Module? If so, what will be the code for Module?

anish11  Thursday, June 21, 2007 6:52 PM

You aren't getting your MessageBox because your code is recursive.

When you load your first instance of Form2, it creates another new instance of Form2. That form loads as soon as you access the TextBox1 property...and when instance of Form2 loads, it creates another new instance of Form2. Which creates another new instance of Form2 and so on.

Your code won't stop until you run out of stack space, and even then it won't stop nicely.

So you need to move the creation of your second form out of the Load event. I suggest creating public properties on your Form2 class, and set the values of these text boxes using those properties.

Christopher Payne  Thursday, June 21, 2007 8:21 PM

You aren't getting your MessageBox because your code is recursive.

When you load your first instance of Form2, it creates another new instance of Form2. That form loads as soon as you access the TextBox1 property...and when instance of Form2 loads, it creates another new instance of Form2. Which creates another new instance of Form2 and so on.

Your code won't stop until you run out of stack space, and even then it won't stop nicely.

So you need to move the creation of your second form out of the Load event. I suggest creating public properties on your Form2 class, and set the values of these text boxes using those properties.

Christopher Payne  Thursday, June 21, 2007 8:21 PM

You can use google to search for other answers

Custom Search

More Threads

• Status pop-up when cpu is being used.
• TypeConverter - GetStandardValues
• Public IP Address
• How to set a column of a DataGridView to display and accept only decimal values?
• VS 2005 Windows App - No Format Toolbar
• How to loop through the resource file of the form
• web service overriding the url property
• Modeless dialog window
• disable window drawing
• Why is only the first shown window focusable?