Using Controls


When a control such as a CheckBox is dropped onto a container, the Windows Forms Designer generates the following code to InitializeComponent:

// UsingControlsSampleForm.Designer.cs partial class UsingControlsSampleForm {   ...   CheckBox checkBox1;   ...   void InitializeComponent() {    this.checkBox1 = new CheckBox();    ...    // checkBox1    this.checkBox1.AutoSize = true;    this.checkBox1.Location = new System.Drawing.Point(185, 100);    this.checkBox1.Name = "checkBox1";    this.checkBox1.Size = new System.Drawing.Size(80, 17);    this.checkBox1.TabIndex = 0;    this.checkBox1.Text = "checkBox1";    this.checkBox1.UseVisualStyleBackColor = true;    ...    // UsingControlsSampleForm    ...    this.Controls.Add(this.checkBox1);    ...   } }


This code declares and creates an instance of the CheckBox control with an initial, default state. It also brings the control under the purview of its container (in this case, the form) by adding it to the Controls collection. This also implicitly sets the control's Parent property to the container and allows the container to manage it and provide support for features such as layout and z-ordering.

Because the Windows Forms Designer's efforts are transparent, generally you need to concentrate only on writing code to configure and use controls. This process is typically driven by the Properties window, shown in Figure 10.2.

Figure 10.2. Declaratively Configuring a Control in the Properties Window


The Windows Forms Designer applies your configuration automatically, producing code similar to what you'd write yourself:

// UsingControlsSampleForm.Designer.cs partial class UsingControlsSampleForm {   ...   void InitializeComponent() {     ...     // checkBox1     this.checkBox1.ThreeState = true;     this.checkBox1.CheckedChanged += this.checkBox1_CheckedChanged;     ...   } } // UsingControlsSampleForm.cs partial class UsingControlsSampleForm : Form {   ...   void checkBox1_CheckedChanged(object sender, EventArgs e) {} }


The result leaves you to fill in the remaining code. In this example, you need to fill in only the CheckedChanged event handler:

// UsingControlsSampleForm.cs partial class UsingControlsSampleForm : Form {   ...   void checkBox1_CheckedChanged(object sender, EventArgs e) {     MessageBox.Show("I am being appropriately handled!");   } }


The same configuration ease applies to any of the myriad controls that come prepackaged in System.Windows.Forms. For a list of the standard Windows Forms controls and where to find more information about them in this book, see Appendix D: Component and Control Survey.




Windows Forms 2.0 Programming
Windows Forms 2.0 Programming (Microsoft .NET Development Series)
ISBN: 0321267966
EAN: 2147483647
Year: 2006
Pages: 216

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net