The Form.Load event is fired every time

I was wondering if I am doing the right thing.

I instantiate the form (let this Form_B) in my class (also the form) and handle the Form_B Load event. In this case, I am doing some initialization.

Form_B can be displayed by the user several times, and I call ShowDialog in my instance variable.

The problem is that Load is called every time I show the form. I tried debugging and also tried using Show () instead of ShowDialog (). Show () does not work when I close the window, but ShowDialog () does not work, but calls Load every time it is displayed.

Is it wrong to continue using the instance after closing the form?

Thanks Stefan

+4
source share
3 answers

Using the Load event to initialize a form is an anachronism from VB6 days. At that time it was really important, which, unfortunately, was done in the design of the Winforms designer. He has loaded the default event for the form.

However, this is not a .NET path; you initialize the class object using the constructor. The only time you need to override OnLoad () (another .NET way, events for code in other classes) is when you care about the size and position of the form. This will not be the size and location of the project when the user changes the Windows theme or launches the video adapter with a higher DPI value. This way you can use OnLoad to move the window or change the controls. This is actually not a very common thing.

So, first fix your problem using the constructor instead. If you still need OnLoad, just use the bool flag, which keeps track of whether it is already running.

private bool initialized = false; protected override void OnLoad(EventArgs e) { if (!initialized) { initialized = true; // etc... } base.OnLoad(e); } 

And yes, this only works if you use ShowDialog (). The form displayed with Show () is automatically deleted when it is closed. This does not happen with ShowDialog () to avoid problems with getting the results of the dialog. Re-creating an instance of the dialog is the best way if you really don't care about saving the last entered values. However, a very expensive way to do this is to create objects that consume a lot of .NET and Windows resources.

+10
source

This is the correct behavior of the Load event, every time it is loaded, it is called. If you want to reuse the form and avoid the Load event, rather than closing the form, you must hide it and use the show method to display it when necessary.

+3
source

The load event is raised after all components of the form are loaded. If you re-render the form, its components are loaded again, and therefore the Load event is fired again.

You can trigger a custom event that will only fire in the form constructor if that is what you are looking for, but I find it bad practice to use the form after it closes.

+2
source

Source: https://habr.com/ru/post/1343804/


All Articles