Home > OS >  C# Access active Form from another active Form
C# Access active Form from another active Form

Time:10-12

Hey I am kinda stuck here and could need a little help or reference.

I have one main form (Form1) and two sub forms (Form2 & Form3). On Form1 is a Panel (Panel1) with two Buttons (Button1 & Button2). If I click Button1 I want to display Form2 inside the Panel of Form1. If I click Button2 I want to display Form3 inside the Panel of Form1.

I got that working already with the following code (Button1 Click):

        Form2.TopLevel = false;
        Panel1.Controls.Add(Form2);
        Form2.FormBorderStyle = FormBorderStyle.None;
        Form2.Dock = DockStyle.Fill;
        Form2.Show();

now to my actual problem. In Form1 I have booleans, integers and strings that I want to reach (read and write) from Form2 and Form3.

Since Form1 and either Form 2 or Form 3 are active I can't just use "Form1 form1 = new Form1;" since initializing a new form doesn't use the already created instance. It's a new form so it has the default values from start and not the changed ones from the active Form1 which I want.

So now I want to have a field in Form2 and Form3 to hold the active instance of Form1 so that I can change and read the values of the actual active Form.

How would I do that?

CodePudding user response:

Pack all data you want to pass from form 1 in a class. ( define a class for this ).

You can define constructors for Form 2 and 3 and pass the instance of type you defined from form 1 to 2 and 3. That is one way of doing this.

Another way is to define properties for Form 2 and 3 and assign values before you call .Show() method. This is not a great idea if your form 2 and 3 can be used some where else and you may accidentally not assign the values to the properties.

CodePudding user response:

Did you create instances of Form2 and Form3 in Form1? If Yes, just add an argument to the constructor of both sub forms.

UPDATED

// In Form1
public partial class Form1 : Form
{
    private readonly Form2 _form2;

    public Form1()
    {
        _form2 = new Form2(this);
        InitializeComponent();
    }
}

// In Form2
public partial class Form2 : Form
{
    private readonly Form1 _form1;

    public Form2(Form1 form1)
    {
        _form1 = form1;
        InitializeComponent();
    }

} 
  •  Tags:  
  • c#
  • Related