Accessing Components from Another Form

Asked

Viewed 7,812 times

4

I have two Forms in my application. A Form for data from an engine that has the following fields: txtPotencia, txtTensao and txtCorrente. I would like to access the values filled in these TextBox through another Form. In the second Form I installed an object of the first Form (Motorform), but I do not have access to TextBox.

public MacroForm()
{
    InitializeComponent();

    MotorForm motorForm = new MotorForm();
    motorForm.Show();
}

Is there any way ?

  • Just so I understand, inside MotorForm has the 3 TextBox, and you need to recover by MacroForm()? first you open the MacroForm and right after the MotoForm()?

  • 1

    That’s right @Virgilionovic

2 answers

4


Yes. Just create these members with public visibility and access the other form.

You can change the visibility of the form controls in the box properties (the same as where the name, text, etc. of the components is changed) and the modifiers for public

Alterando a visibilidade pela caixa properties

It is also possible to change the file. Form designer, however, is not a good idea since this code is written by Visual Studio, so it may end up being rewritten if some visual modification is made to these components.

public MacroForm()
{
    InitializeComponent();

    var motorForm = new MotorForm();
    var potencia = motorForm.txtPotencia.Text; 
    //Desde que txtPotencia seja public, isso é válido
}

If you don’t want to directly expose the controls of form as Textboxes, etc. It is possible to create public methods (or getters and setters) to change these values

However, keep in mind that the more components are "shared" the more code will need to be written in this case. Quite possible that all this code is useless if the real need is just to recover/settar values for the controls.

  • How do I change the visibility of the textbox ?

  • @Raphaelpradodeoliveira I put an example

3

Within the MotorForm brood 3 methods that will assist in the recovery, since the TextBox the visibility is private and I don’t particularly like to change that.

public class MotorForm: Form
{
    public string Potencia 
    {
        get { return txtPotencia.Text; }
    }
    public string Tensao
    {
        get { return txtTensao.Text; }
    }
    public string Corrente
    {
        get { return txtCorrente.Text; }
    }
}

with these 3 methods will have the values of the 3 TextBox.

public MacroForm()
{
    InitializeComponent();

    MotorForm motorForm = new MotorForm();
    motorForm.Show();

    // já consegue recuperar os valores dos TextBox
    motorForm.Potencia; 
    motorForm.Tensao;
    motorForm.Corrente;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.