C# Tutorial - Hello Parameter Windows StyleWe are going to create a simple application that allows you to enter your name and click on a button, that will launch a dialog that says hello to you. All of this will be done with two controls and a single line of code. So follow these simple steps to create the application, then we will take a look at what is going on.
When you run the application, your form is displayed. ![]() If you enter a name into the textbox and click on the button, another dialog is displayed which displays the message “Hello” plus whatever you entered into the textbox. ![]() ControlsThe Button and Textbox that you added to the form are known as controls. These are what make up most windows applications such as notepad or word. When you look at the code in Form1.cs, you do not see any code for either of these controls, this is because the IDE has added all of the code for these two controls into Form1.Designer.cs. If you open this file like you did before, we can examine what has been added. At the bottom of the code, the two controls have been added as private members. This means that two references have been allocated on the heap, but the objects cannot be used yet. private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; At this point, the InitializeComponent method is minimized, expand it out and you will see that the IDE has done three things. First off, code to instantiate the controls has been added using the new keyword. The new keyword is used to create objects on the heap and invoke their constructors. private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
. . .
}
Secondly the controls are initialized to a given state depending on where you placed them on the form. private void InitializeComponent()
{
...
//
// button1
//
this.button1.Location = new System.Drawing.Point(5, 25);
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;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(112, 30);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 1;
...
}
Finally, the controls are added to the forms Controls member, so that it knows that it has to tell them to draw themselves, when the form is drawn. private void InitializeComponent()
{
...
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
...
}
|