2

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 connection 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

Community
  • 1
  • 1
Kornel
  • 263
  • 4
  • 16

4 Answers4

2

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:)

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
  • Thank you, So I would resume as that static information can go to constructor and dinamically handled information would be in a better place in the Load event. – Kornel May 21 '11 at 21:05
2

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.

Furnes
  • 382
  • 1
  • 2
  • 19
  • Thanks, I agree with the readability question, but if your code grows too much calls would affect performance. For right now I am following your suggestion as I started like that, method calling. – Kornel May 21 '11 at 21:11
1

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.

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
0

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!

danyolgiax
  • 12,798
  • 10
  • 65
  • 116