Transferring data from the first form to the second. It gives an error: The object reference does not indicate an object instance.

//Form1 public FormChoise FormChoise1; FormChoise1 = new FormChoise(); FormChoise1.InputString = "M|G"; FormChoise1.Owner = this; FormChoise1.Show(); public void DelMess(int hap_del, string source_) {"hi"} //Form2 public string InputString; Form1 formMain; //равен null string OutString = "hi"; formMain.DelMess(1, OutString); //Ошибка: Ссылка на объект не указывает на экземпляр объекта 

What can be done?

    1 answer 1

    You can overload the desired form and pass the link / object there.

    For example, we want to open form 2 and set the desired value there (In this example, we in Form2 pass the object we need, which we then assign to the required, internal variable, which will allow us to use it without difficulty later on):

     private string Value; public Form2(string val) { InitializeComponent(); Value = val; } 

    And the challenge:

     Form2 form2 = new Form2("Hello!"); form2.Show(); 

    Another example, we want to run Form2 and call the one we need from Form1 (In this example, we can pass a link to the first form and work with it):

     public Form2(Form1 form) { InitializeComponent(); form.MyMethod("World!"); } 

    Form 1:

     //... Form2 form2 = new Form2(this); form2.Show(); //... public void MyMethod(string aa) { MessageBox.Show(aa); } 
    • The fact is that I get the value in the second form, but I cannot assign the result of the calculations to the variable of the first form, I cannot transfer those back. string OutString = "hi"; formMain.DelMess(1, OutString); where the last public void DelMess(int hap_del, string source_) {"hi"} at this place an error occurs: The link to the object does not indicate an object instance - zayana
    • @zayana Well, you understand that by writing Form1 formMain; - you only create an empty object without initializing it (`= new Form1 ();), this gives you an error. You need to either initialize as I just wrote (if the form is not open yet), or from the first form pass a link to this form to the desired form (as I indicated in the answer) and then use it. - EvgeniyZ
    • Everything turned out to be easy, thanks for responding! - zayana