How to access members of Form1 from Form2?

0

I want to access members of Form1 using Form2 . For example, I want to change the color of the "panel1" that is inside the "Form1" to the black color:

This is how I'm doing

public partial class Form2 : Form
{
   public Form2()
   {
      InitializeComponent();
   }

   private void Form2_Load(object sender, EventArgs e)
   {
      Form1 form1 = new Form1();
      form1.panel1.BackColor = Color.Black;
   }
}

However, it is impossible to do this, because the control "panel1" does not appear within the Form1 class "instantiated".

    
asked by anonymous 23.02.2018 / 18:15

3 answers

2

The easiest way to do this is to create a method in form1 that changes the color of the panel.

Next, create a property on form2 that receives form1 and pass form1 on opening form2 Then, when opening form2 , access this property and call the method.

/////
//form1
////
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void btn_abrir_form2_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.form1 = this;
        form2.Show();
    }
    public void Mudar_BackColor()
    {
        this.BackColor = Color.Aquamarine;
    }
}      

/////
//form2
////
public partial class Form2 : Form
{
    public Form1 form1 { get; set; }
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        form1.Mudar_BackColor();
    }
}
    
23.02.2018 / 18:48
4

The controls you add to the form are not directly accessible because they do not represent object properties. For this there is a "Controls" property in the form class to be able to make these changes.

        Form2 frm = new Form2();
        frm.Controls["panel1"].BackColor = Color.Blue;
        frm.Show();

Second senario:

    public Form mudaCor { get; set; }

    private void Form2_Load(object sender, EventArgs e)
    {
        mudaCor.Controls["panel1"].BackColor = Color.Blue;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2();
        frm.mudaCor = this;
        frm.Show();
    }
    
23.02.2018 / 18:30
3

The code of the shared example.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Nova instancia.
        Form2 frm = new Form2();

        //Passar form1 para o form2
        frm.parentForm = this;
        frm.Show();
    }
}

For FORM2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    /// <summary>
    /// 
    /// </summary>
    public Form parentForm { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {
        parentForm.Controls["panel1"].BackColor = Color.Blue;
    }
}
    
23.02.2018 / 22:15