views:

235

answers:

3

Looks like there is no Load event for usercontrol on the CF.

I'm used to loading data on the Load EventHandler.

What is the other alternative to achieve this for CF?

So far looks like I have no choice but to do so in the Contructor of the usercontrol...

A: 

You can use the EnabledChanged event and check if the control is enabled for the first time:

private void UserControl1_EnabledChanged(object sender, EventArgs e)
{
    if (Enabled && firstTime)
    {
        firstTime= false;
        //DO init
    }
}
Matthieu
+2  A: 

I deleted my previous answer as it was absolute rubbish. You're 100% correct, there's no Load event for the CF. Turns out I discovered this myself when I wrote my UserControl. I looked for the load event on an old project, in which all my user controls are inheriting from my own base class... called UserControlBase.

I appear to have implemented my own Load functionality within my base class. This is a cut down version of my base class:

public class UserControlBase : UserControl
{

    public UserControlBase() { }

    public event EventHandler Load;

    private void Loaded()
    {
        if (this.Load != null)
        {
            this.Load(this, new EventArgs());
        }
    }

    public new void ResumeLayout()
    {
        this.Loaded();
        base.ResumeLayout();
    }

    public new void ResumeLayout(bool performLayout)
    {
        this.Loaded();
        base.ResumeLayout(performLayout);
    }

}

Now, in your actual user control, do the following:

public partial class UserControl1 : UserControlBase
{

    public UserControl1()
    {
        InitializeComponent();
    }

    private void UserControl1_Load(object sender, EventArgs e)
    {

    }

}

This is from a very old project. In later projects I tend to just have a .Load() method on user controls that is called in the Form_Load.

GenericTypeTea
Thanks, I think I'll go with a simple Load method on the usercontrol. And in the form, it will call the load method.
pdiddy
Sounds like a good plan!
GenericTypeTea
Um... what this works? "new" only overrides the call if that explicit type definition is referenced. If .ResumeLayout() is called via UserControl or Control it wont call the "new" version.
Quibblesome
No, but the form.designer.cs file calls UserControl1.ResumeLayout() on InitializeComponent(), so this 'hack' works. But like I also said, adding a physical 'Load' method is the best way forward.
GenericTypeTea
A: 

I would use the OnHandleCreated, but remember, a Control's handle can be recreated.

E.x.:



private bool _loaded;

protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
if(!_loaded)
{
_loaded=true;
DoLoad();
}
}

private void DoLoad()
{
}


hjb417

related questions