Referencing control on one form from another form

后端 未结 8 1993
轻奢々
轻奢々 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:02

    Make a private field. Right click 'Refactor', select 'Encapsulate Field'. This will automatically create a public property for the field.

    Another approach is to overload the public constructor.

    public CustomersForm(string property1, string property2...)
    {
         //Get the properties and do what is necessary.
    }
    
    //Parent Form
    
    CustomersForm frmCustomers = new CustomersForm(property1, property2..);
    

    Also sending the complete control to another form is not a good strategy. Share only the fields that are necessary via public properties/constructors.

    0 讨论(0)
  • 2020-12-12 02:15

    A better way to approach this is to pass a reference of a control into your class, change any property of it there with your logic, then "send" it back to the calling form.

    The trick here is to make sure the class code is using the "ByRef" argument in the called class or else this will not work. In memory you are referencing the same control without creating new properties for it, and that lessens code creep.

    For instance here is how you can disable a button from your class code.

    In the form, call your class and pass it the button (or any other control):

    ' new the class your calling
    Dim CallClass As New ProgramCall
    ' pass the control as a by reference argument
    CallClass .SetUpTheCall("HOURLY", btnSendToBank)  
    

    Then, in your class:

    Public Sub SetUpTheCall(ByVal ParmToPass As String, ByRef btnSendToBank As Button)
    
    ' your class logic goes here...
    
    ' disable the send button on the calling form
    btnSendToBank.Enabled = False
    
    ' change the button text on the calling form
    btnSendToBank.text = "Disabled"
    
    0 讨论(0)
提交回复
热议问题