Reputation:
How do you reference an existing object in vb.net?
To describe my problem more specifically, I have my main form Form1
that loads when I start the application. Form1
has a datagridview dgv1
. I have another form form2
in the project with a bunch of textboxes. On clicking a button on Form1
I create an instance of form2
. From form2
how do I reference the existing form1
to populate dgv1
with input from the texboxes on form2
?
Upvotes: 2
Views: 1429
Reputation: 27342
Easy fix: You can access a control on Form1
directly from Form2
So if you have DataGridView1
on Form1
, in the Form2
code you can access it by using Form1.DataGridView1
Note: this is not a good design, because you are tightly coupling your two forms, you would be better to pass a reference to a DataGridView into Form2 rather than updating it directly
in the Constructor of Form2 force it to pass your reference:
Public Class Form2
Private _dgv As DataGridView
Public Sub New(dgv As DataGridView)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'ensure we have a value object
If dgv Is Nothing Then Throw New ArgumentNullException("DataGridView")
_dgv = dgv
End Sub
Private Sub frmRibbonTest_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Dim rect = RibbonControl1.ClientRectangle
DataGridView1.Location = New Point(rect.X, rect.Y)
DataGridView1.Height = rect.Height
DataGridView1.Width = rect.Width
End Sub
End Class
Then when you create form2 from form1, use your reference like this:
Dim f2 = New Form2(Me.DataGridView1)
f2.Show()
Upvotes: 1
Reputation: 155708
You need to pass a reference-to-Form1
to Form2
. Use the Me
keyword to get a reference to the object currently executing:
In Form1.vb
:
Sub Form1_OpenForm2()
Dim form2 As New Form2()
form2.AcceptForm1( Me )
form2.Show()
End Sub
In Form2.vb
:
Private _form1 As Form1
Public Sub AcceptForm1(form1 As Form1)
_form1 = form1
End Sub
Upvotes: 1