robintw
robintw

Reputation: 28571

Pass value to form in .Net

I want to pass an integer value to a form in .Net so that it can load the right data. I'm using this so that when I double click on a record in a list, a form opens with the data from that record loaded so it can be edited. What is the best way to do this? Should I create a property and set it before calling the Show() method, or should I overload the constructor or something and send the value in as an initialisation value that way?

Note - this doesn't need to work with sending more than one value in to the form - only one value will be needed.

It shouldn't really matter but this is in C++ .Net.

Upvotes: 0

Views: 564

Answers (3)

Rune Grimstad
Rune Grimstad

Reputation: 36330

Add a new constructor that takes the argument and calls the default constructor. By keeping the default constructor you can still use the Visual Studio forms designer, and all your new constructor needs to do is to store the value.

Or you can just add a public property that stores the value. Then you create an object of the forms class, sets the property, and shows the form.

Upvotes: 0

Vincent Van Den Berghe
Vincent Van Den Berghe

Reputation: 5575

Make it obligatory in the constructor. It wouldn't make sense to have one of these forms anyway if you don't have something to edit.

Upvotes: 0

Asher
Asher

Reputation: 1867

I'd suggest something else.

create a static method (to the form you want to open) - pass the parameter to the static method.

leave it up to the static method to new up the form, load the data and call the Show method.

this way the calling form doesn't have to mess with the form to much (ctor, setting the value, calling show) - you keep this logic away and encapsulated in the form - which means you can also re-use it without copying the code.

Upvotes: 4

Related Questions