从另一个表单引用一个表单上的控件 [英] Referencing control on one form from another form
问题描述
如您所料,我对 .NET 有点陌生,只想从另一个表单引用一个表单上的控件.
As you can guess, I'm kind of new to .NET and just want to reference a control on one form from another.
通常我只会做 Form.Control.Property 但这不起作用,而且我通过 Google 找到的每个示例都不适用于我.
Usually I would just do Form.Control.Property but that doesn't work and every example I've found through Google doesn't work for me.
公共类等似乎过于复杂
有没有更简单的方法来做到这一点?我已经准备好认输了,现在只使用一个全局变量.
Is there a more simpler way to do this? I'm ready to throw in the towel and just use a global variable at this point.
我有一个包含我想要引用的控件的表单,frmGenerate 有一个名为 txtCustomerNo 的文本框.
I have the form containing the control I want to reference, frmGenerate which has a textbox called txtCustomerNo.
从这个表单到一个按钮的点击事件,我想显示另一个表单 frmCustomers,并让该表单引用 txtCustomerNo 中的值.
From this form through a button's click event I want to show another form, frmCustomers, and have that form reference the value in txtCustomerNo.
frmCustomers.ShowDialog()
它必须是一些我没有掌握的简单的东西.
It has to be something simple that I'm just not grasping.
推荐答案
在你要引用的控件所在的表单中:
In the form with the control you want to reference:
Public Property CustomerNo() As TextBox
Get
Return txtCustomerNo
End Get
Set(ByVal Value As TextBox)
txtCustomerNo = Value
End Set
End Property
在您希望引用控件的表单中:
In the form you wish to reference the control:
Dim CustomerNo as string = _sourceForm.CustomerNo.Text
这样做是一个糟糕的设计,但它是最简单的方法 - 应该让你走上正轨.
It's a bad design to do this, but it's the simplest method - and should set you on your way.
如果您只对文本框中输入的值感兴趣,那么以下可能更好:
If you are only interesting in the value entered in the text box then the following might be better:
Public ReadOnly Property CustomerNo() As String
Get
Return txtCustomerNo.Text
End Get
End Property
以上将要求第二个表单引用第一个表单的实际实例.将以下内容添加到第二个表单中:
The above will require the second form to have a reference to the actual instance of the first form. Add the below to the second form:
Private _sourceForm as frmGenerate
Public Property SourceForm() As frmGenerate
Get
Return _sourceForm
End Get
Set(ByVal Value As frmGenerate)
_sourceForm = Value
End Set
End Property
现在您可以执行以下操作来处理第二个表单的创建和启动:
Now you can do the following where you handle the creation and startup of your second form:
Dim customersForm as new frmCustomers
customersForm.SourceForm = Me
customersForm.Show()
我在这里为您构建了一个示例项目:
I have constructed a sample project for you here:
http://www.yourfilelink.com/get.php?fid=595015
这篇关于从另一个表单引用一个表单上的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!