broke
broke

Reputation: 8302

Is there an event that fires after load for a user control?

I'm using User Controls in C# winforms, and I would like some code to be executed after the load event, and after the control has been shown. If no such event exists, is it possible to make one?

Upvotes: 2

Views: 6325

Answers (2)

huMpty duMpty
huMpty duMpty

Reputation: 14470

  1. Create a public method in user control
  2. Call the method on Parent win-form Shown Event

This will call the code you want to run once.

You can also use user-control paint event, but this will Expensive call. Because your code will execute every time the control is redrawn.

So it is better to use a flag which you can determine whether to run the code or not

i.e.

  private bool _run =true;

  private void Control_Paint(object sender, PaintEventArgs e)
        {
            if(!_run) return;
            //call the code you need to run
           _run = false;
        }

Upvotes: 0

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61509

You could use one of events from this list. OnPaint would be most likely candidate.

Form Events:

Construtor
Load
Layout
Activated
Paint­
Closing
Closed
Deactivate
Dispose

and for Controls:

Enter
GotFocus
Leave
Validating
Validated
LostFocus

If you can't find one that fits you needs, this article explains how to construct and fire event.

Upvotes: 2

Related Questions