[英]How to reference an existing object in VB.net?
How do you reference an existing object in vb.net? 您如何引用vb.net中的现有对象?
To describe my problem more specifically, I have my main form Form1
that loads when I start the application. 为了更具体地描述我的问题,我有主窗体Form1
在启动应用程序时加载。 Form1
has a datagridview dgv1
. Form1
具有一个datagridview dgv1
。 I have another form form2
in the project with a bunch of textboxes. 我在项目中还有另一个表单form2
,其中有一堆文本框。 On clicking a button on Form1
I create an instance of form2
. 单击Form1
上的按钮后,我将创建一个form2
实例。 From form2
how do I reference the existing form1
to populate dgv1
with input from the texboxes on form2
? 如何从form2
引用现有的form1
来填充来自form2
上dgv1
的输入的dgv1?
You need to pass a reference-to- Form1
to Form2
. 您需要将对Form1
的引用传递给Form2
。 Use the Me
keyword to get a reference to the object currently executing: 使用Me
关键字获取对当前正在执行的对象的引用:
In Form1.vb
: 在Form1.vb
:
Sub Form1_OpenForm2()
Dim form2 As New Form2()
form2.AcceptForm1( Me )
form2.Show()
End Sub
In Form2.vb
: 在Form2.vb
:
Private _form1 As Form1
Public Sub AcceptForm1(form1 As Form1)
_form1 = form1
End Sub
Easy fix: You can access a control on Form1
directly from Form2
轻松解决:您可以直接从Form2
访问Form1
上的Form1
So if you have DataGridView1
on Form1
, in the Form2
code you can access it by using Form1.DataGridView1
因此,如果在Form1
上具有DataGridView1
,则在Form2
代码中,可以使用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 注意:这不是一个好的设计,因为您将两个表单紧密地结合在一起,所以最好将对DataGridView的引用传递到Form2中,而不是直接对其进行更新。
in the Constructor of Form2 force it to pass your reference: 在Form2的构造函数中,强制其通过您的引用:
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: 然后,当您从form1创建form2时,使用如下引用:
Dim f2 = New Form2(Me.DataGridView1)
f2.Show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.