Tuyen Phan Tuyen Phan - 1 month ago 11
ASP.NET (C#) Question

Correct way to pass info

So I've been thinking.

When you create a form and use applicaton.run(form1). And within that form1 you open another form2 and hide form1. Within form2 you open another form3 and hide form 2. But in form3 you want to use the info(variables) provided in form1 which is not ?accessible? correct me if I'm wrong.

I've thought about several ways, but I dont think they are the correct way.

  1. Save the info from form1 in a static class.

  2. Create all forms objects in the main class and close/run them 1 by 1.

  3. Pass the info(variables) from form1 to form2 to form3.

What is the correct way to do this?

I am sorry if its hard to follow.


It depends. If these are dialog forms shown as modals and there's only one or two variables then it's often OK to store the values as properties in the class for that form and just examine it in the same way as you with DialogResult on a standard MessageBox form.

If its more complicated or the forms are staying open, then you'd want to create an object and pass that to the forms. Remember objects are passed by reference, so if you create a class called MyDataContainer, and then create an instance in the main form, then pass that instance to the other forms, it is the same instance in each of those forms. So if form3 updates that instance, the other forms will be able to see those changes too.

Ps: avoid the static route, there is very rarely a valid use case for that.