I create a new form and call from the parent form as follows:
loginForm = new SubLogin();
loginForm.Show();
I need to display the child form at the centre of the parent. So,in the child form load I do the foll:`
Point p = new Point(this.ParentForm.Width / 2 - this.Width / 2, this.ParentForm.Height / 2 - this.Height / 2);
this.Location = p;
But this is throwing error as parent form is null. I tried setting the Parent property as well, but didn't help. Any inputs on this?
In event childform load
If you want to calculate your own location, then first set
StartPosition
toFormStartPosition.Manual
:Where this is the main/parent form, just like Location.X.
Default value for
StartPosition
isFormStartPosition.CenterParent
and therefore it changes the child's location after showing.Why not use this?
(vb.net)
There seems to be a confusion between "Parent" and "Owner". If you open a form as MDI-form, i.e. imbedded inside another form, then this surrounding form is the Parent. The form property StartPosition with the value FormStartPosition.CenterParent refers to this one. The parameter you may pass to the Show method is the Owner, not the Parent! This is why frm.StartPosition = FormStartPosition.CenterParent does not work as you may expect.
The following code placed in a form will center it with respect to its owner with some offset, if its StartPosition is set to Manual. The small offset opens the forms in a tiled manner. This is an advantage if the owner and the owned form have the same size or if you open several owned forms.