1

When I try to call a method on form1 from form2, as per the following code, nothing happens:

form2:

Form1 form1 = new Form1();
form1.AddToListView();

form1:

public void AddToListView()
{
    AddList();
    listView1.Items.Add("Test", "Test", 0);
    label1.Text = "Test";
}

What am I doing wrong?

5

2 Answers 2

5

With Form1 form1 = new Form1(); you are creating a new instance of the form, not referencing your main form1 which I'm assuming is your problem.

You either need to pass the reference of form1 to form2's constructor, or discard your current form1 and change form2 to:

Form1 form1 = new Form1();
form1.Show();
form1.AddToListView();
2
  • But the form is already open...
    – Mariogrip
    Sep 8, 2013 at 17:21
  • 3
    An instance of your form might be open, but it's not the one that you are affecting with your call to AddToListView. You can make and show hundreds of the same form if you wish, but calling a method on one of them wont affect the others (unless you make them static).
    – Alfie
    Sep 8, 2013 at 17:23
-1

As Alfie said, when you create a new instance of Form1 it has nothing to do with the current running instance which you could probably find created and run in Main method in Program.cs file in your solution:

static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1()); // THIS INSTANCE
        }

It would be better you become more familiar with Object Oriented Programming (OOP) if you have difficulty understanding this. In past programming languages like VB6 we only had one Form1. But in OOP like C# you could have thousands instances of Form1, more informally speaking thousands of Form1.

However perhaps the best solution to what you want to do is to change the default way of running Form1:

static class Program
    {
        public static Form1 myForm1;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            myForm1= new Form1 ();
            Application.Run(myForm1);
        }

    }

and use this to manipulate the instance:

Program.myForm1.AddToListView();

By the way, doing so seems quite unnatural to me in sense of OOP. Please add comments about any ideas you might have about this ?

1
  • I appreciate if the down voter tells me what's wrong with my answer?
    – Ehsan88
    Sep 12, 2013 at 17:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.