Home > database >  How to call Form 1's method from Form2 without static and new class();?
How to call Form 1's method from Form2 without static and new class();?

Time:03-03

How to call Form 1's method when Form is resized without static and new class(); like below codes. because more than one new class(); The "System.StackOverflowException" issue is causing when the code is used. it does not take the values it saves in the class due static.

Form1 class code:

Form2 frm2 = new Form2();
public void ResizePicture(int Height, int Width)
{
    frm2.pictureBox1.Height = Height;
    frm2.pictureBox1.Width = Width;
}

private void button1_Click(object sender, EventArgs e)
{
    frm2.pictureBox1.Image = Image.FromFile(@"C:\Users\Omer\Desktop\screenshot.png");
    frm2.Show();
}

Form2 class code:

private void Form2_Resize(object sender, EventArgs e)
{
    ResizePicture(this.Height, this.Width);
}

CodePudding user response:

You can subscribe to the Resize event of the other form

In Form1:

private readonly Form2 frm2;

private Form1()
{
    InitializeComponent();

    frm2 = new Form2();
    frm2.Resize  = Frm2_Resize;
}

private void Frm2_Resize(object sender, EventArgs e)
{
    ...
}

This code only creates a Form2 once in the constructor of Form1. Now the Resize event handler of Form2 is in Form1.


Another possibility is to pass a reference of the first form to the second one

In Form2:

private readonly Form1 frm1;

private Form2(Form1 frm1)
{
    InitializeComponent();

    this.frm1 = frm1;
}

private void Form2_Resize(object sender, EventArgs e)
{
    frm1.ResizePicture(this.Height, this.Width);
    // Note: `ResizePicture` must be public but not static!
}

In Form 1

frm2 = new Form2(this); // Pass a reference of Form1 to Form2.

CodePudding user response:

Another one, passing Form1 via Show() itself:

private void button1_Click(object sender, EventArgs e)
{
    frm2.pictureBox1.Image = Image.FromFile(@"C:\Users\Omer\Desktop\screenshot.png");
    frm2.Show(this); // <-- passing Form1 here!
}

In Form2, you cast .Owner back to Form1:

private void Form2_Resize(object sender, EventArgs e)
{
    Form1 f1 = (Form1)this.Owner;
    f1.ResizePicture(this.Height, this.Width);
}
  • Related