Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading