0
votes

In C# I have two forms "Form1" and "Form2". Form1 creates images that are stored in a folder. Form2 displays the number of images in that folder.

Say I have made 2 images with Form1 and then I open Form2. Form2 now says there are 2 images. Now while keeping both forms open I want to be able to add a new image and Form2 updates. At the moment if I use Form1 to add more images while Form2 is open Form2 continues to display the number of images that were in the folder when Form2 opened.

I have found solutions that involve Form2 closing and reopening but I don't want this. It's jarring for the user having windows opening and closing every time they press a button. I just want Form2 to update live as I make changes with Form1.

Any help would be greatly appreciated!! Thanks!

2
See the following info about events.Mark Benningfield

2 Answers

0
votes

You can do this with public method in Form2

In Form1 you need to save Form2 object in property

FORM 1

    public partial class Form1 : Form
    {
        public Form2 MyProperty { get; set; }
        public Form1()
        {
            InitializeComponent();
        }

        // for opening form 2
        private void button1_Click(object sender, EventArgs e)
        {
            
            Form2 f2 = new Form2();
            f2.Show();
            MyProperty = f2;
        }


        // adding new image
        private void button_ADD_Click(object sender, EventArgs e)
        {
            MyProperty.updateCounter();
        }
    }

When you add new image, then you can call the metoh from Form2 to update counter.

In FORM 2 you need crate PUBLIC method to update counter

 public partial class Form2 : Form
    {
    

        public Form2()
        {
            InitializeComponent();
            // default value
            label1.Text = "0";
        }

        // update counter
        public void updateCounter()
        {
            label1.Text = (int.Parse(label1.Text) + 1).ToString();
        }

    }
0
votes

You may want to take a look at events and delegates. Basically, whenever you do something to Form1 that can affect other forms, you want to trigger an event. In Form2, you have a method which you call whenever that event triggers. This way you can have multiple forms open, and as long as you set them to "listen" to a given event, they can all react.

You can read more about them here, in the Microsoft Documentation.