| re: How to access Form2 from Form1
I see these types of questions here all the time. Unfortunately they arise due to improper design.
C# is an object oriented language not a Form oriented language. When creating a project in C#, the first step is to design your objects not your forms. Forms represent the view part of objects. You should not have Forms called form1,form2 e.t.c, rather you should have UserDetailsForm, InvoiceForm e.t.c. i.e the forms model objects.
What does that have to do with how to open one form from another?
Well the answer is that there are many ways of allowing form's controls to access, create or influence other forms or controls on other forms.
The correct way of doing it depends on what objects the forms are representing. e.g If they model a composition relationship i.e one of the objects being modeled is a member of the other object, then the correct way would be to create the member form as an instance variable of the containing form (as you did above). For other relationships, other techniques are needed.
The problem with hacking away at the keyboard providing handles to all forms everywhere just so the code works is that you create a huge bowl of spaghetti too difficult to digest in the near future when you shall surely need to add some seasoning to it. Just making a few additions later would create serious headaches on all the housekeeping issues that would be required. Usually people just go on and add other more ugly hacks when that happens so that the program works again e.t.c.
Better take a step back and do object oriented programming instead. It really is so much more simpler.
P.S I probably sound harsh and ranty but it's just I've been seeing these kinds of questions for far too long now.
|