Ruby
Ruby

Reputation: 969

Access Form1 controls from Form2

Have two forms-Form1 & Form2.Form1 has a button(btnNew),which opens Form2 on click, and is disabled.I need to enable the button again, only when Form2 is closed.User needs to use Form1 also simultaneously.This code is not enabling the button again. Where am I missing.

In Form1:

private void btnNew_Click_1(object sender, EventArgs e)
  {   
    Form2 f2 = new Form2();
    f2.Show();
    btnNew.Enabled = false;
  }   
public void EnableButton()
 {
    btnNew.Enabled = true;
 }

In Form2:

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
  {
    Form1 f1 = new Form1();
    f1.EnableButton();
  }

Upvotes: 0

Views: 687

Answers (2)

user1914530
user1914530

Reputation:

Subscribe to your Form2 closing event from within the class that is instantiating it (Form1).

private void btnNew_Click_1(object sender, EventArgs e)
  {   
    Form2 f2 = new Form2();
    f2.Closing += f2_Closing;
    f2.Show();
    btnNew.Enabled = false;

  }   

public void f2_Closing(object sender, FormClosingEventArgs e)
{
   this.EnableButton();
}

public void EnableButton()
 {
    btnNew.Enabled = true;
 }

Upvotes: 0

Brad
Brad

Reputation: 84

You code creates a new Form1 which will be different from the one already running in your application.

You could try adding a reference to Form1 in your Form2 and operate on it's controls that way.

Give form2 a property like:

public Form ParentForm {get; set;}

And assign it form1 in your button click:

Form2 f2 = new Form2()
f2.ParentForm = this;
f2.show();

Then in your closing you should be able to do something like:

this.ParentForm.EnableButton();

Upvotes: 1

Related Questions