CIS Logo SVC Logo

   Computing & Information Systems


Schoology Facebook        Search CIS Site      Tutorials

Software Design Using C++

Second Intermediate Windows Forms Example

The Changes

Take your previous Windows Forms App, made with the directions for C#, and modify it as follows. Essentially we add error-checking to the code.

private void CalculateButton_Click(object sender, EventArgs e)
   float Area, Length, Width;

      Length = Convert.ToSingle(LengthTextBox.Text);
      Width = Convert.ToSingle(WidthTextBox.Text);
      if ((Length > 0) && (Width > 0))
         Area = Length * Width;
         AreaTextBox.Text = Convert.ToString(Area);
         AreaTextBox.Text = "Area undefined";
   catch (Exception ex)
      AreaTextBox.Text = "Exception " + ex;

As you can surmise from the code, the Area Undefined message is shown if a Length or Width value is zero or negative. Such values would not make sense when we go to find the area of a rectangle. Also, a try...catch... construct is used to handle any exception that gets raised by the code that gets the Length and Width from the text boxes, calculates the area, and sets the answer into another text box. Without this try...catch, you can easily get an exception (which results in a run-time error) by clicking on the Calculate button without filling in anything in the text boxes for Length and Width. With the above try...catch... added, the answer text box will display the text of the exception and there is no run-time crash of your program.

Try It Out

Save all of your files. Build your project and then start it without debugging. Hopefully you have it working on the first attempt!

If you wish you can also run your program by finding the executable file in My Computer and double clicking on it. It will probably be inside a Debug folder that is within a bin folder. The filename would be Area2.exe or something similar (consisting of the project name with the .exe extension added).

Back to the main page for Software Design Using C++

Author: Br. David Carlson with contributions by Br. Isidore Minerd
Last updated: November 21, 2014