tonFrere wrote:
Hello again,
I think I'm doing well so far, thanks to you guys.
Could you just validate this code. Maybe there's a better way to do
things, I'm just not 100% sure about that code. The results are there
but I would rather do things right.
This is from my forms dictionary class constructor. It's how I add each
form to the dictionary:
Form2 f2 = new Form2();
add(f2.Text, f2);
REM: The "code" I'm using is the form header. I just have to make sure
it's the same name in the database.
Then, on my click event, I open the correct form using that code in a
try/catch block:
dictProjet.TryGetValue("Form2", out nouvForm);
nouvForm.Show();
Works well, just wonder if it's "swell" ;)
This code does something different from what I originally understood.
I thought that you would fetch from the database an indication of
_which type_ of form to create, and then instantiate that form.
The code you just posted instantiates all of the forms and then shows
them based on a value read from the database.
I was thinking of something more along these lines (please note that
this is written for .NET 1.1; someone else can no doubt provide a
superior implementation using generics):
Hashtable formTypes = new Hashtable();
formTypes["DBCODEFORFORM1"] = typeof(Form1);
formTypes["DBCODEFORFORM2"] = typeof(Form2);
....
The important thing to notice here is that the codes used to look up
the form types don't correspond to any property of the form. That way,
you can change the form title, or even the form name, and you don't
have to fix your database tables.
Once you have the table set up, when you retrieve a code from the
database you can create the form using System.Reflection:
using System.Reflection;
Type typeOfFormToCreate = (Type)formTypes[codeFromDatabase];
if (typeOfFormToCreate == null)
{
... error: bad code in database ...
}
else
{
ConstructorInfo ci =
typeOfFormToCreate.GetConstructor(Type.EmptyTypes) ;
if (ci == null)
{
... error: Form has no public no-argument constructor ...
}
else
{
Form newForm = (Form)ci.Invoke(null);
... do something with the newly created form ...
}
}
One important difference between this code and yours is that you can
create multiple instances of the same form this way, if you want to.