You are on page 1of 2

5/9/2017 C#InitializeComponentMethodDotNetPerls

Go Windows:Controls Top27WindowsExamplePages...

InitializeComponent.InWindowsFormswecreateprogramsvisually.We
dragcontrolstotheForminVisualStudio.Behindthescenes,VisualStudio
addscodetotheInitializeComponentmethod,whichiscalledintheForm
constructor.

Form

Example.Inthiscodesample,weseetheInitializeComponentmethodwhenanew
programiscreated.Then,weseeInitializeComponentafteraddingaButtoncontrolby
draggingonetotheWindowintheDesigner.

Also:
Weseethatstatementsforbutton1wereaddedtothecontents.VisualStudioaddedthe
SuspendLayoutandResumeLayoutmethodcalls.

InitialcontentsofInitializeComponent:C#

///<summary>
///RequiredmethodforDesignersupportdonotmodify
///thecontentsofthismethodwiththecodeeditor.
///</summary>
privatevoidInitializeComponent()
{
this.components=newSystem.ComponentModel.Container();
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.Text="Form1";
}

ContentsafteraddingButton:C#

///<summary>
///RequiredmethodforDesignersupportdonotmodify
///thecontentsofthismethodwiththecodeeditor.
///</summary>
privatevoidInitializeComponent()
{
this.button1=newSystem.Windows.Forms.Button();
this.SuspendLayout();
//
//button1
//
this.button1.Location=newSystem.Drawing.Point(13,13);
this.button1.Name="button1";
this.button1.Size=newSystem.Drawing.Size(75,23);
this.button1.TabIndex=0;
this.button1.Text="button1";
this.button1.UseVisualStyleBackColor=true;
//
//Form1
//
this.AutoScaleDimensions=newSystem.Drawing.SizeF(6F,13F);
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize=newSystem.Drawing.Size(292,273);
https://www.dotnetperls.com/initializecomponent 1/2
5/9/2017 C#InitializeComponentMethodDotNetPerls
this.Controls.Add(this.button1);
this.Name="Form1";
this.Text="Form1";
this.ResumeLayout(false);
}

Donotmodify.ItisbestnottomodifytheInitializeComponentmethod,butinsome
casesitmaybeusefulto.Sometimes,whencreatingaprogramyoumayremovea
ControlandtheInitializeComponentmethodwillnolongercompile.

And:
Inthiscase,youcanfindthecompilationerrorandfixit,usuallybyremovinglines.

CompileTimeError

Discussion.Whenyoucreateanewprogram,theInitializeComponent()callislocatedin
theForm1constructorbody.Shouldyouaddcodebeforeorafterthiscall?Ifthecode
doesn'tinteractwiththecontrols,eitherlocationisfine.

However:
Ifthecodedoesinteractwiththecontrols,youwillwanttoputthecodeafterthe
InitializeComponentcall.

Also,youcancreateaForm1_Loadeventhandler.Youcandothisbydoubleclickingon
theFormintheDesigner.ThiswillrunaftertheForm1constructor.Thisisagoodwayto
separateyourcodefromtheInitializeComponentcall.

Summary.WelookedattheInitializeComponentmethodintheC#language
andWindowsFormsplatform.TheInitializeComponentmethodcallis
implementedwithapartialclasstomakeyourpartofthecodeeasiertoedit.

Partial

https://www.dotnetperls.com/initializecomponent 2/2

You might also like