1

Normally, if you want to set properties on a form, you can construct the form, set the properties and then showthe form. This gives you time to set the properties before the Load event is raised.

Code would look like follows:

MyForm form = new MyForm();
form.PropertyA = ...;
form.PropertyB = ...;
form.ShowDialog(this);

A user control also has a load event. If you put this user control on a form, then the Load event of the user control is raised at the end of the form's InitializeComponent(). So during construction of the form, way before the properties of the form are set.

If one of the properties of the form must be passed to the user control, then you are too late.

The solution I use now is give the user control an initialize function, that would do the things the user control would do during the Load event. This initialize function is called during the form's Load.

Although this works, this seems like bypassing Microsoft's way of initializing forms. What is the proper way to load a user control if it needs some property values that are only known at run time?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • I think the user control Loaded event only fires when the control is rendered, and that wont happen until it is added to a parent. So setting the properties before adding the control to a parent control seems like the equivalent of the form method you have shown – musefan Dec 04 '13 at 15:33
  • I agree with @musefan. I just tried this, and the user control's OnLoad() method is not called until the `form.ShowDialog()` method is called. So the form's properties will be set BEFORE the user control's OnLoad() is called - so there's no problem? – Matthew Watson Dec 04 '13 at 15:40
  • In fact, all control events happen _just after_ the corresponding event on page. See http://stackoverflow.com/a/7335271/1236044 – jbl Dec 04 '13 at 15:49
  • I think the OP has accidentally used the `forms` tag when he meant to use the `Windows Forms` tag. – Matthew Watson Dec 04 '13 at 15:55
  • The solutions given here don't work if you use the designer. The designer uses the default constructor, sets all properties thar were set using the designer and then adds them to the Form's controls member. This is all done in InitialeComponent, whis is called during construction of the form. If you add it during runtime you can't see it in the designer – Harald Coppoolse Dec 05 '13 at 22:26

0 Answers0