PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

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

 May 06, 2022     c#, call, image, methods, resize     No comments   

Issue

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);
}

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.


Answered By - Olivier Jacot-Descombes
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing