C# Tutorial - Adding Two Numbers Windows Style


We are going to create a simple application that allows you to enter two numbers and display the result.

  1. Create a new Windows Forms Application called WApp03.

  2. Click on the Label control in the Toolbox and then click on the form. To move the label click and drag it around the form until you are happy with its position.

  3. Change the text property in the properties box to "Value 1:".

  4. Add a second Label underneath with the text property set to "Value 2:".

  5. Click on the Textbox control in the Toolbox and then click on the form. Move this as before until you are happy with it.

  6. Add a second Textbox underneath.

  7. Add a button with the text property set to "Calculate".

  8. Double click on the button. This will create a stub method for the Click event of the button. Change the method so that it is the same as shown below.

    private void button1_Click(object sender, EventArgs e)
    {
      int a = Convert.ToInt32(this.textBox1.Text);
      int b = Convert.ToInt32(this.textBox2.Text);
      int r = a + b;
      String str = a + " + " + b + " = " + r;
      MessageBox.Show(str, "result");
    }

When you run the application, your form is displayed.

And when you enter numbers and click on the button, a MessageBox appears with the sum in it.

The Label Control

In this application we used a new control named a Label. The Label control is commonly used to provide descriptive text for other controls, such as text boxes. They can also be used to add descriptive text to a Form to provide the user with helpful information such as run time information on the status of an application.

Instead of using a MessageBox, we could create our own form comprising of a Label and a Button, which would display the same as that shown above


<< Previous Contents Next >>

© Publicjoe, 2008