C# Good Style for Form initialization [duplicate]
Possible Duplicate:
How should the Form.Load event be used compared to its constructor method?
Hello,
My question is regarding good programming practices in C#. If I'm creating a application with various forms I would initialize the conn开发者_StackOverflow中文版ection to DB inside the Load method, or it should be inside the basic Constructor of the form? As well the other code to fill the forms basic textboxes and comboboxes can be inside the Load method or it is always better to use the constructor for that purpose?
Thanks in advance,
Kornel
Whenever you want to change the state of a control that belongs to a Form, I suggest you doing this in the Form Load event.
Doing that in the constructor of the form is error prone. Have you thought about what would happen if you try to do it in the constructor, but before the InitializeComponents()
method call?
About the ConnectionString, you could do that in both, because that isn't really directly related with the Form.
You could also take a look at some open-source projects codes, to see how they do that about the ConnectionString
or some other stuff not related with the Form:)
On a site note.. never do anything directly in the constructor or form load.
Create a init method or something that you call from the appropriate method (constructor,load). This makes refactoring and unit testing easier.. And the code is often easier to read.
Definitely better to do in the form Load
, because that way it will only happen when needed. But also agree with the suggestion to use an init method you call from your form load event handler.
I vote for connection in constructor and form fill in Load method!
I think also that there is not a big difference... it depends from application implementation! For example you can inherit all your forms from a base form and put there connection string retrieve logic.
If you want to go deeper I suggest you to look at dependency injection (search for windsor castle, spring.net, ninject...) to inject database access classes inside form classes!
精彩评论