Change text from another form does not work

1

Follow the code below:

Form2:

public void ChangeLabel(string s)
{
    labelX1.Text = s;
}

And inside Form1:

private void button_MostrarSegundaTela_Click(object sender, EventArgs e)
{
    if (Screen.AllScreens.Length > 1)
    {
        //Estendido
        SegundaTela formulario = new SegundaTela();
        Screen[] telas = Screen.AllScreens;
        Rectangle bounds = telas[1].Bounds; // pode ser outro índice.
        formulario.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height);
        formulario.StartPosition = FormStartPosition.Manual;
        formulario.Show();
    }
    else
    {
        //Duplicado, ou apenas 1 tela
        MessageBox.Show("Estender");
    }
}

private void label3_TextChanged(object sender, EventArgs e)
{
    var result = label3.Text;

    SegundaTela frm2 = new SegundaTela();
    frm2.ChangeLabel(result);
}

The idea is: When changing label of form1, also change label of form2.

It does not work. Apparently nothing.

Any solution?

    
asked by anonymous 20.10.2017 / 01:27

1 answer

3

In the code that you try to change the value of the label a new instance of the form is being created.

That is, the instance being displayed is intact.

Move the form variable to a more comprehensive scope and use this variable to call the method that changes the value of the label.

Something like this:

public class SuaTela
{
    SegundaTela telaSecundaria;

    private void button_MostrarSegundaTela_Click(object sender, EventArgs e)
    {
        if (Screen.AllScreens.Length > 1)
        {
            telaSecundaria = new SegundaTela();
            // resto do código 
            telaSecundaria.Show();
        }
    }

    private void label3_TextChanged(object sender, EventArgs e)
    {
        var result = label3.Text;
        telaSecundaria?.ChangeLabel(result);
    }
}
    
20.10.2017 / 02:38