views:

309

answers:

3

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.

+4  A: 

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.

Asher
smells like a factory of a single type. good suggestion.
kenny
actually this is not a factory, since the static method doesn't return anything. it just does the job (creating a form, loading data into it and showing it).
Asher
A: 

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.

Vincent Van Den Berghe
A: 

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.

Rune Grimstad