Forms are classes like any other, just create properties or make public controls to access.
The method you used works because all controls are stored in the Controls
collection of the Form and are accessible in the same way as an array, informing the key (in this case the name) of the control. But in addition to getting messy code, try changing the name of one of the controls, not even the refactoring of the IDE will update the changes and will bring a terrible problem.
There are other ways to do what you need, as I said above, you can create public properties and access from another object. Example:
No Form1:
public partial class Form1 : Form
{
public string PropriedadeForm1 { get; set; }
public string LabelForm1 { get { return labelForm1.Text; } set { labelForm1.Text = value; } }
public Form1()
{
InitializeComponent();
}
private void buttonAbrirForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show(this); //Passa a instância do Form1 (this) como Owner da instância do Form2
}
private void buttonSetPropriedadeForm2_Click(object sender, EventArgs e)
{
Form2 form2 = this.OwnedForms.OfType<Form2>().FirstOrDefault(); //Seleciona a instância do Form2 que é 'Owned' por esta instância do Form1
if (form2 != null) //Se há um Form2
{
form2.PropriedadeForm2 = textBoxForm1.Text; //Define a propriedade
}
}
}
Notice public properties PropriedadeForm1
and LabelForm1
, they will be accessible from outside the Form.
Note also that when instantiating Form2, this
was passed as a parameter of the Show
method. This causes the instance of Form2 to be owned by this instance of Form1. Later, we can access them by the OwnedForms
properties of Form1, and Owner
of Form2.
Now an example of Form2:
public partial class Form2 : Form
{
public string PropriedadeForm2 { get; set; }
public Form2()
{
InitializeComponent();
}
private void buttonMostraLabelForm1_Click(object sender, EventArgs e)
{
Form1 form = this.Owner as Form1;
if (form != null)
MessageBox.Show(form.LabelForm1);
}
private void buttonSetLabelForm1_Click(object sender, EventArgs e)
{
Form1 form = this.Owner as Form1; //Pega a instância do Form1 que é dona desta instância do Form2
if (form != null)
form.LabelForm1 = textBoxForm2.Text;
}
private void buttonPropriedadeForm2_Click(object sender, EventArgs e)
{
MessageBox.Show(this.PropriedadeForm2);
}
}
Result:
Thereisalsothepossibilityofmakingthefieldspublic,andaccessingthemfromoutsidetheForm:
Inthisway,toaccesslabelForm1itsuffices:
privatevoidbuttonMostraLabelForm1_Click(objectsender,EventArgse){Form1form=this.OwnerasForm1;if(form!=null)MessageBox.Show(form.labelForm1.Text);}
Ifyouusethisforminyourcode,insteadof:
TabControltabControl1=(TabControl)form1.Controls["tbControl1"];
would be:
form1.tbControl1;
or
form1.LbTeste.Text = "Teste Label";