0

In my program I have two forms. The main form and a form where you fill in extra information. What I'm trying to do is to write out the information given on the second form on a list box when the 'ok' button is pressed.

Currently this is what I have: Main form:

public void writeLine()
{
    foreach (var item in VarClass.listItems[VarClass.count - 1])
    {
        listBox1.Items.Add(item.ToString());
    }
}

Second form:

Form1.writeLine();

As it, I get the following error at 'Form1.writeLine();' "An object reference is required for the non-static field, method or property..."

I can kinda fix this by making 'writeLine()' static in the main form, but then I get the same error on 'listBox1' in the main form. How do I fix this?

2
  • Your second form needs a reference to the first. Commented Feb 14, 2018 at 15:38
  • It's a question that gets to the heart of object oriented programming. You need a reference to the actual Form object that was instantiated (ie: Created). Form1 is the class, not the object here. Commented Feb 14, 2018 at 15:39

4 Answers 4

1

You should pass the reference of your main form to the second form and call the method on that reference. For example you can create a property on the second form like private Form _mainForm; and create a constructor of the second form to receive that reference and set to that field. After that you will be able to call _mainForm.writeLine() in your second form.

Sign up to request clarification or add additional context in comments.

Comments

0

Create an instance of Form1 and call the method. Here is the code:

new Form1().writeLine();

Comments

0

There are a couple ways to handle this. One is for form2 to have a reference back to the calling form ideally through an interface rather than a reference to the concrete class.

Another option would be for Form2 to have an event that form1 could subscribe to that would inform form1 that form2 has some output.

Comments

0

Keep a reference to the second form from the first:

public MyFirstForm
{
    ...

    public MyFunction()
    {
        MySecondForm secondForm = new MySecondForm();

        // ... Open your form etc, look for when it's complete and then ...

        // Read the values from the second form into the first
        var MyValues = secondForm.getValues();

        // Now populate the list-box with the information returned.
        //for (my listbox)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.