2

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?

2
  • 1
    Consider adding methods to your forms so FormA can tell FormB to populate its own controls. Commented Jul 21, 2016 at 0:38
  • 1
    Why don't you try module? Commented Jul 21, 2016 at 6:54

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Windows Forms controls are not Public by default, though, so he'll also need to make controls he needs in Form1 public or write Public Properties for the specific things he wants to be able to do.
@JoelCoehoorn - controls are Friend by default so should be fine to access from another form
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.