It really depends on your use case. Ask yourself these questions:
- Does my code perform operations on the UI?
- Does my code require information from the form or about the form?
- Does my code perform a time consuming operation?
If the answer to any of these is yes, then I think the best solution is to override the OnLoad method and execute the code you want there. This is debatable regarding the time consuming code case. However, if your code performs any operation on the UI, you should definitely take this approach.
protected override void OnLoad(EventArgs e)
{
// Your code here
}
NOTE: You can also subscribe to the Load event, which will yield a similar result, but is only recommended for very specific cases.
If your code isn't related to the UI itself, then using the constructor is the simplest solution, and will likely work just fine. However, there are a few caveats to this approach. First off, you have to remember that the constructor runs when the form is instantiated, regardless of whether or not its ever displayed. Additionally, make sure that you place that code after the call to InitializeComponent()
, to prevent any delays in opening the form.
I'm giving you the succinct version. For a more detailed explanation, I recommend you give this and this answer by Hans Passant a quick read. He has some great information about the difference between Load
and OnLoad
, as well as when to use one of those two and when to use the constructor.