Referencing control on one form from another form

后端 未结 8 2046
轻奢々
轻奢々 2020-12-12 01:30

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 does

8条回答
  •  难免孤独
    2020-12-12 02:01

    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

提交回复
热议问题