0

I have two forms. Form1 has a label, Form2 has a button. I'm adding Form2 to Form1 as a control. When I click the button I want the label to update.

Code for Form1:

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

    private void RunTest()
    {
        Form myForm2 = new Form2();
        myForm2.TopLevel = false;
        this.Controls.Add(myForm2);
        myForm2.Show();
    }

    public static void UpdateLabel()
    {
        label1.Text = "Button Pressed";   //ERROR
    }
}  

Code for Form2:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form1.UpdateLabel();
    }
}  

Calling the UpdateLabel() require it to be static, but then I can't update Label1.Text

Do you have any suggestions what I should do in this situation? I want to add many Form2 to Form1 when I get this to work.

ola
  • 11
  • 2

1 Answers1

0

In Form2 add a Property of Type Form1 and assign it with this from Form1.

private void RunTest()
{
    Form myForm2 = new Form2();
    myForm2.otherform = this;              // <--- note this line
    myForm2.TopLevel = false;
    this.Controls.Add(myForm2);            // TODO: why is this line here?
    myForm2.Show();
}

You can then

private void button1_Click(object sender, EventArgs e)
{
    otherform.UpdateLabel();
}

if you make UpdateLabel() non-static

public void UpdateLabel()
{
    label1.Text = "Button Pressed";
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222