0

I have 2 Forms and I can open Form2 from Form1 but when I try to update a label in Form1 from from Form2 the label is not updated. Following is my code of Form1

public Form1()
    {
        InitializeComponent();
    }
    void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 'S'|| e.KeyChar == 's')
        {
            var myForm = new Form2();
            myForm.ShowDialog();
            myForm.BringToFront();
        }
    }

    public string LabelText
    {
        get
        {
            return this.label2.Text;
        }
        set
        {
            this.label2.Text = value;
            this.label2.Refresh();
        }
    }

Form 2 code for updating Form1 label is following

Form1 form1Func;
private void updateCounterBtn_Click(object sender, EventArgs e)
    {
        form1Func = new Form1();
        form1Func.LabelText = "09";
        form1Func.Refresh();
    }

So even though there is no error and using break point I am able to observe that lable2.Text is updated in debugger (using break point and watch) but in Form1 UI lable2 remains same and is not updated. How can I solve my problem?

prattom
  • 1,625
  • 11
  • 42
  • 67
  • 1
    The proximate problem here is that instead of using the original `Form1` object, you are creating a brand new `Form1` object, setting the text, and then promptly throwing that `Form1` object away. However, the broader issue is that your `Form2` object shouldn't need to know about `Form1` at all in the first place. Whether you decide to address that or not, the marked duplicate provides information for allowing the form objects to interact in a successful way. You can either pass the `Form1` object reference to `Form2`, or you can use an event in `Form2` that `Form1` can subscribe to. – Peter Duniho Apr 16 '17 at 05:08
  • Thanks for the explanation – prattom Apr 16 '17 at 08:05

0 Answers0