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

Changing variables from one form in another form

Is there a way to change variables that are in Form1 from Form2?
I tried using method in Form1, and calling it from Form2.
Here is a method in Form1 to change variables that I wrote:

public void change(int newval)
{
    val = newval;
}

I tried calling it in Form2 by:

form1.change(newval)

where form1 would be passed in through a constructor:

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

Form1 form1;
public Form2(Form1 form1)
{
    this.form1 = form1;
    InitializeComponent();
}

But I can’t find a way to get Form1 as an object to pass it into the constructor.

>Solution :

A simple way to make form1 accessible globally as Program.form1:

public static class Program
{
    public static Form1 form1;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        form1 = new Form1();
        Application.Run(form1);
    }
}
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