Do I use the Paint event to position controls at runtime?

.net, c#, controls, resize, winforms

Solution

No; that is certainly the wrong way to do it. `Paint` can fire very often; you should do as little work in it as possible. (and you certainly shouldn't modify the layout)

Instead, you should set the `Anchor` and `Dock` properties in the designer so that it will all happen automatically.

Problem

I am fairly new to C# programming coming from VB6 so please be gentle :P I have been using Panels to group controls (i.e. Panels contains Textbox, Labels, Listview, etc.) and then have the panel align itself at run-time so that the controls align in different resolutions. However, I am doing this from the Panel's Paint routine(?) i.e.: ``` private void pnlTop_Paint(object sender, PaintEventArgs e) { btnExit.Location = new Point(this.Width - (this.Left + lblTitleMain.Left + btnExit.Width), 10); btnMinimize.Location = new Point(this.Width - (this.Left + lblTitleMain.Left + (btnExit.Width * 2)), 10); btnSettings.Location = new Point(this.Width - (this.Left + lblTitleMain.Left + (btnExit.Width * 2 + btnExit.Width)), 10); lblTitleMain.Left = (((this.ClientSize.Width - lblTitleMain.Width) / 2) / 2) / 2; lblTitleMain.Top = btnExit.Top + lblTitleMain.Height; int intMenuY = lblTitleMain.Bottom + 5; lnkMenuSystem.Location = new Point(lblTitleMain.Left + 3, intMenuY); lnkMenuDeployment.Location = new Point(lnkMenuSystem.Right + 50, intMenuY); lnkMenuTables.Location = new Point(lnkMenuDeployment.Right + 50, intMenuY); lnkMenuTCP.Location = new Point(lnkMenuTables.Right + 50, intMenuY); lnkMenuDCM.Location = new Point(lnkMenuTCP.Right + 50, intMenuY); lnkMenuProcessData.Location = new Point(lnkMenuDCM.Right + 50, intMenuY); lnkMenuGenerateReports.Location = new Point(lnkMenuProcessData.Right + 50, intMenuY); lineMenuButtom.StartPoint = new Point((((this.ClientSize.Width - lblTitleMain.Width) / 2) / 2) / 2, lnkMenuSystem.Top + lnkMenuSystem.Height + 10); lineMenuButtom.EndPoint = new Point(this.Width - (this.Left + lblTitleMain.Left), lnkMenuSystem.Top + lnkMenuSystem.Height + 10); lnkMenuErrorMessage.Location = new Point(lnkMenuSystem.Left, lineMenuButtom.Y1+5); lnkMessageWelcome.Location = new Point(lineMenuButtom.X2 - lnkMessageWelcome.Width, lineMenuButtom.Y2 + 5); GlobalVariables.intGeneralLeft = lineMenuButtom.StartPoint.X; GlobalVariables.intGeneralWidth = lineMenuButtom.X2; } ``` What I want to ask is this: Is this the proper way to do it? The reason for this was because I am uncertain if this will impact performance once the application runs on old systems (assuming that it would be used in XP with 2g RAM Pentium 4 HT or equivalent System).

Original source