InitializeComponent
In Windows Forms we create programs visually. Behind the scenes, Visual Studio adds code to InitializeComponent
, which is called in the Form constructor.
It is recommended that you do not modify the InitializeComponent
method. Sometimes, deleting lines from InitializeComponent
can fix a compile-time error.
We see the InitializeComponent
method when a new program is created. Then, we see InitializeComponent
after adding a Button
control using the Designer.
SuspendLayout
and ResumeLayout
method calls./// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "Form1"; }/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(13, 13); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); }
It is best not to modify the InitializeComponent
method. Sometimes, you may remove a Control and the InitializeComponent
method will no longer compile.
Should you add code before or after InitializeComponent()
in the Form1
constructor? If the code doesn't interact with the controls, either location is fine.
InitializeComponent
call.Form1_Load
event handler. This is a good way to separate your code from the InitializeComponent
call.We looked at the InitializeComponent
method. The InitializeComponent
method call is implemented with a partial class
to make your part of the code easier to edit.