Reputation: 253
I have a listBox that I would like to carry out a method when its loaded up, although I can't use the Form "On_Load" trigger, since the ListBox is within a TabControl.
Is there a way of getting a method to execute when the object initializes?
Upvotes: 2
Views: 3474
Reputation: 67
You can use OnHandleCreated(EventArgs e). However, it triggers during design time too. You can override it too.
Upvotes: 1
Reputation: 887195
You can just put your code in the constructor.
You usually don't need to wait for any initialization.
Upvotes: -1
Reputation: 4143
Have the same problem, the previous answers apply well, for a single case.
But, I require to do something in most controls, in several forms, in an app. Solved by using an interface:
interface IOnLoad
{
void OnLoad();
}
And added to descendant control:
public partial class MyButton : Button, IOnLoad
{
void OnLoad() { // call "OnLoadDelegate" }
}
public partial class MyForm : Form
{
public void MyForm_Load(...) {
foreach(Control eachControl in Controls) {
if (eachControl is IOnLoad) {
IOnLoad eachOnLoadControl = (IOnLoad)eachControl;
eachOnLoadControl.OnLoad();
}
} // foreach
}
} // class
Its more complex, but it suit my requirements.
Upvotes: 1
Reputation: 48129
As @SLaks stated, you could put in your class's constructor. However, if what you want to prepare relies on other elements in the form, you can add to the event handler queue at the end of a form loading, but before its actually presented to the user.
In the constructor code of your form (not the designer code), add to the load event, then add your own custom function
public partial class frmYourForm : Form
{
public frmYourForm()
{
Load += YourPreparationHandler;
}
private void YourPreparationHandler(object sender, EventArgs e)
{
// Do you code to prepare list, combos, query, bind, whatever
}
}
Upvotes: 2
Reputation: 185583
The closest analog for controls is the HandleCreated
event. This will fire when the underlying control handle is created, which is slightly before the Loaded
event of the parent window would fire.
Upvotes: 3