Accessing components from another Form

2

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 entered in these TextBox through another Form . In the second Form I instantiated an object of the first Form (MotorForm), however I do not have access to TextBox .

public MacroForm()
{
    InitializeComponent();

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

Is there anyway?

    
asked by anonymous 31.01.2017 / 13:54

2 answers

4

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

You can change the visibility of form controls in the properties box (the same one where you change the name, text, etc. of the components) and change the modifiers to public

Itisalsopossibletochangetheform.Designerfile,howeverthisisnotagoodideasincethiscodeiswrittenbyVisualStudio,soitmayendupbeingrewrittenifsomevisualmodificationismadetothesecomponents.

publicMacroForm(){InitializeComponent();varmotorForm=newMotorForm();varpotencia=motorForm.txtPotencia.Text;//DesdequetxtPotenciasejapublic,issoéválido}

IfyoudonotwanttodirectlyexposetheformcontrolssuchasTextBoxes,etc.Youcancreatepublicmethods(orgettersandsetters)tochangethese

However,keepinmindthatthemorecomponentsthatare"shared" the more code will need to be written in that case. It is very possible that all this code is useless if the real need is just to retrieve / set values for the controls.

    
31.01.2017 / 13:58
3

Within MotorForm create 3 methods that will aid recovery, since TextBox visibility is private and I particularly do not 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 3 TextBox .

public MacroForm()
{
    InitializeComponent();

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

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