Search code examples
c#formsstack-overflow

C# access variable from form 1 with form 2


I want to access variables and such from form 1 to form 2, I have one main form and then open another with some indicators, a timer keep rolling in form 2 to check variables and lists in form 1 and light or darken the indicators. But I get "Stack overflow exeption" se picture

This is the code:

public partial class Form1 : Form
{
    Diagnostik formDiagnostics = new Diagnostik();

Button that opens form 2:

private void buttonDiagnostics_Click(object sender, EventArgs e)
    {

        formDiagnostics.Show();
    }

Form 2:

public partial class Diagnostik : Form
{
    Form1 form1 = new Form1();

Timer:

private void updateGUI_Tick(object sender, EventArgs e)
    {
        if (Convert.ToBoolean(form1.ListServo1Inputs[0]) == true) { indicatorS1Di1.BackColor = Color.Green; }
        else { indicatorS1Di1.BackColor = Color.Gray; }

Error screen dump picture


Solution

  • You need to pass form1 into the constructor for formDiagnostics:

    public partial class Form1 : Form
    {
        private Diagnostik formDiagnostics;
    
        public Form1()
        {
            formDiagnostics = new Diagnostik(this);
        }
    

    In the Diagnostik contructor, store the Form1 argument into a field/property:

    public partial class Diagnostik : Form
    {
        private Form1 form1;
    
        public Diagnostik(Form1 form1)
        {
            this.form1 = form1;
        }
    

    You can then access your private Diagnostik.form1 field:

    private void updateGUI_Tick(object sender, EventArgs e)
    {
        if (Convert.ToBoolean(form1.ListServo1Inputs[0]) == true) { indicatorS1Di1.BackColor = Color.Green; }
        else { indicatorS1Di1.BackColor = Color.Gray; }