0

I have the method listviewupdate() in usercontrol schuler. Usercontrol schuler is in form1. Then I have form2. When I click a button in form2 I want to call the method listviewupdate().

I tried creating a second method in form1 which calls the listviewupdate() method, and then calling this second method in form 2 but I get an error. Can somebody please help me?

Cicciopasticcio
  • 195
  • 1
  • 2
  • 8

2 Answers2

0

In your file Program.cs, you can define a globally accessible variable:

static class Program
{
    //  for external access to Form1 methods
    public static Form1 MainForm;

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

The static variable MainForm can then be used to access any public method to Form1 via Program.MainForm.MyMethod().

Assuming, you have access to the Form2 object from within Form1, you can use the Form2 object variable to call Form2 methods out of Form1 methods.

Be aware that you might run into problems when (unknowingly ...) using more than one thread. Read about BeginInvoke.

Axel Kemper
  • 10,544
  • 2
  • 31
  • 54
0

@Axel Kemper thanks for the response. I did how you told me with Program.MainForm.MyMethod() but it didn't find MyMethod(). Then I went in the form1.Designer and there I saw that the usercontrol was set to private, also I switched it to public and now it works with Program.MainForm.schuler1.MyMethod() //schuler1 is the name of my user control.

I just don't understand why it doesn't work with

Form1 form1 = Application.OpenForms[1] as Form1; form1.schuler1.ListviewUpdate(); //schuler1 is the name of my usercontrol

even if the user control is set to public I get the error "System.NullReferenceException" in main.schuler1.ListviewUpdate();

Cicciopasticcio
  • 195
  • 1
  • 2
  • 8
  • Use `Application.OpenForms[0]` to get the first form as explained [here](https://stackoverflow.com/q/21564542/1911064). – Axel Kemper Jun 04 '19 at 20:50