Since you open Form1
, inside it you have a command that opens Form2
, and in Form2
, a button to add tabPage
to Form1
, the code should look like this :
Form1.cs:
//Evento que abre o Form2
private void buttonAbrirForm2_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Parent = this;
form.Show();
}
Form2.cs:
//Evento que adiciona a tab no Form1
private void buttonAddTabForm1_Click(object sender, EventArgs e)
{
Form1 f1 = ((Form1)this.Parent);
var tab = new TabPage();
var aba = new Abas();
tab.Text = "Guia " + ((int)f1.tabControl1.TabCount + 1).ToString();
f1.tabControl1.TabPages.Add(tab);
tab.Controls.Add(aba);
f1.tabControl1.SelectTab(tab);
aba.Dock = DockStyle.Fill;
}
There is still no way to pass Form1
to Parent
of Form2
, and from anywhere in the application you access Form1
:
private void buttonAddTabForm1_Click(object sender, EventArgs e)
{
foreach (Form f in Application.OpenForms)
{
if (f is Form1)
{
Form1 f1 = ((Form1)f);
var tab = new TabPage();
var aba = new Abas();
tab.Text = "Guia " + ((int)f1.tabControl1.TabCount +1).ToString();
f1.tabControl1.TabPages.Add(tab);
tab.Controls.Add(aba);
f1.tabControl1.SelectTab(tab);
aba.Dock = DockStyle.Fill;
break;
}
}
}
As I said in the comments, I believe this is not the situation for creating a custom userControl. But anyway I made one that changes Form1, and here it worked perfectly:
Example:
//Evento do botão que está dentro do userControl1
private void button1_Click(object sender, EventArgs e)
{
if (this.Parent is Form1)
{
((Form1)this.Parent).Text = "Texto foi alterado pelo controle";
}
}
In the case of your Control:
private void button5_Click(object sender, EventArgs e)
{
if (this.Parent is Form1)
{
Form1 f1 = ((Form1)this.Parent);
var tab = new TabPage();
var aba = new Abas();
tab.Text = "Guia " + ((int)f1.tabControl1.TabCount + 1).ToString();
f1.tabControl1.TabPages.Add(tab);
tab.Controls.Add(aba);
f1.tabControl1.SelectTab(tab);
aba.Dock = DockStyle.Fill;
}
}
Note: In order for you to access controls outside the form, the modifiers
property must be set to public