Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vb.net - Referencing control on one form from another form

As you can guess, I'm kind of new to .NET and just want to reference a control on one form from another.

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.

It just seems overly complicated with public classes, etc.

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.

I have the form containing the control I want to reference, frmGenerate which has a textbox called 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

EDIT: I have constructed a sample project for you here:

http://www.yourfilelink.com/get.php?fid=595015


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...