CIS Logo SVC Logo

   Computing & Information Systems


Schoology Facebook        Search CIS Site      Tutorials

Calculator Web App

The Goals for this Example

One goal is to see how to use buttons and text boxes in a web app. Another is to construct a web app that does some easy calculations. In addition you see how to put a class into the App_Code folder and use it in your web app. Technically it is a part of a web site.


Note that this example was partially inspired by the calculator example on pages 78 - 81 of the book Professional ASP.NET 4.5 in C# and VB by Gaylord, Wenz, Rastogi, Miranda, and Hanselman. However, the example on this page gives a more complete set of calculator functions, so that the resulting calculator is more useful.

The Calculator Example

The following lists all of the pieces of this calculator web app in one place.

Creating the Example

This section outlines the directions for building this web app.

Placing a Class in the App_Code Folder

  1. Begin by starting Visual Studio 2012 or later.
  2. We assume that you already have at least one solution with a web site within it, the one created in the previous example. If not, go back and do that first example. Open that solution, which you can probably find under File, Recent Projects and Solutions.
  3. If you do not already have an App_Code folder for this web site, right click on the web site in Solution Explorer, select Add, Add ASP.NET Folder, App_Code.
  4. Then right click this App_Code folder and select Add, Add New Item, Class. Be sure that VB is selected instead of C#, name your file Calculator.vb, and click Add.
  5. Place this code for a simple Calculator class into your Calculator.vb file and save it. Note that this MyCalculator class provides 5 similar functions: Add, Subtract, Multiply, Divide, and Power. Each takes 2 value parameters named x and y and returns its answer in the function name.
  6. This is a good spot to save all of your files. You can use File, Save All or click the button for this.

Working with the Form

  1. Right click your web site in Solution Explorer and select Add, Add New Item, Web Form. Make sure that VB, not C#, is the selected language. Name your file Calc.aspx and make sure that the check box for "Place code in separate file" is checked. Then click the Add button.
  2. As you go through the following directions, look at the completed form to see what you are aiming for.
  3. If the web form isn't on the screen, open it by double clicking Calc.aspx in Solution Explorer.
  4. If necessary, use View, Properties Window and View, Toolbox so that these 2 items are available.
  5. Change the title of the form document to Calulator. This is probably easiest in Source view, where you simply type Calculator between the opening <title> and closing </title> tags.
  6. Be sure that your web form is open in Design View, not Source view. (Split view might work reasonably as well.)
  7. Add the following controls to your web form by dragging them from the Toolbox:
    1. Four labels whose Text properties (in the Properties list for the label) are set to Calculator, x, y, and Answer. Change the font of the Calculator one to bold, which you can find under the Font property.
    2. Three text boxes with IDs of xTextBox, yTextBox, and AnswerTextBox. Change the ReadOnly property of AnswerTextBox to be true, as we do not want the user to be able to change an Answer that's in this text box.
    3. Seven buttons with Text properties of x + y, x - y, x * y, x / y, x ^ y, x <-- Answer, and y <-- Answer. Change the IDs of these buttons to be something descriptive such as AddButton, Subtract Button, MultiplyButton, DivideButton, PowerButton, AnswerToX, and AnswerToY respectively.
  8. Now, how do you line up the controls so that they fit on the form in the desired layout? Click on each control in turn and then on Format, Set Position, Absolute. Then drag the bottom edge of the div so that it is big enough to hold all of the controls. You should then be able to drag each control to its desired location. If you have trouble getting this to work in Design View, you can switch to Source View and adjust the value for the style attribute of each control so that it is the same or similar to what I have for the style information. For example, to have the buttons line up in a row they all have to have the same top position. (I used 135 pixels, taken from the top of the browser window.) Another way to line up the tops of the buttons is to use control-click on each button in Design View and then use Format, Align, Tops.
  9. Don't forget to save all of your files.

Adding Click Handler Code

  1. Double click the x + y button on your form. This will take you to an editor where you can add the code that should be executed when a user clicks on this button. In the same way, double click on each of the other six buttons on your form. This will give you an outline of the click handler for each of the buttons.
  2. Note that the click handler for the add button will be named AddButton_Click and is a subroutine, a function that returns nothing in the function name. The click handlers are all located in the file Calc.aspx.vb.
  3. Add to the click handler outlines so that the code is as shown in my Calc.aspx.vb file.
  4. Do not forget to add the line Dim myCalc As New MyCalculator, as that adds an object of the MyCalculator class, thus giving you access to the class functions we wrote for this in the App_Code folder.
  5. Below you see the complete code for Calc.aspx.vb in case it is easier to just paste some or all of it in. Be careful if you named any of the controls differently than I did, however. Let's look more closely at two representative example functions in this code: the click handlers AddButton_Click and AnswerToX_Click.
    1. AddButton_Click places into the Text field of AnswerTextBox the result of applying the myCalc.Add function to the two desired numbers and then using the ToString() function to convert that number answer to a string so that it can be assigned into the Text field of AnswerTextBox.
    2. AnswerToX_Click is simpler: It simply assigns the string from the Text field of AnswerTextBox into the Text field of xTextBox. There is no need to convert to a number and then back into a string.

Partial Class Calc
    Inherits System.Web.UI.Page

    Dim myCalc As New MyCalculator

    Protected Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
        AnswerTextBox.Text =
            myCalc.Add(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    End Sub

    Protected Sub SubtractButton_Click(sender As Object, e As EventArgs) Handles SubtractButton.Click
        AnswerTextBox.Text =
            myCalc.Subtract(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    End Sub

    Protected Sub MultiplyButton_Click(sender As Object, e As EventArgs) Handles MultiplyButton.Click
        AnswerTextBox.Text =
            myCalc.Multiply(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    End Sub

    Protected Sub DivideButton_Click(sender As Object, e As EventArgs) Handles DivideButton.Click
        AnswerTextBox.Text =
            myCalc.Divide(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    End Sub

    Protected Sub PowerButton_Click(sender As Object, e As EventArgs) Handles PowerButton.Click
        AnswerTextBox.Text =
            myCalc.Power(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    End Sub

    Protected Sub AnswerToX_Click(sender As Object, e As EventArgs) Handles AnswerToX.Click
        xTextBox.Text = AnswerTextBox.Text
    End Sub

    Protected Sub AnswerToY_Click(sender As Object, e As EventArgs) Handles AnswerToY.Click
        yTextBox.Text = AnswerTextBox.Text
    End Sub
End Class

Build Your App

  1. Save all of your files.
  2. Then use Build, Build Website.
  3. If the build succeeded, the Output window will give you a message to that effect.
  4. If not, take a look at the error messages to see if you can tell what went wrong and fix it.
  5. You can close the Output window to get it out of your way.

Testing and Debugging The App

  1. Click the button with the green triangle and labeled with the name of a brower (perhaps Edge) to see your web app running using a simple web server running on your local machine via a certain port. (Equivalently, you can click on Debug, Start Without Debugging.) For example, you might see a URL of http://localhost:2576/Calc.aspx in your browser. In this particular case, port 2576 was used to communicate with the simple web server, but you might well get a different port number. Note that next to the green arrow is a pull-down which will allow you to select from a list of available browsers.
  2. Put some numbers in the text boxes and try clicking the various buttons to see if they function as expected.
  3. If the app does not produce the desired results, check your code and the IDs for the text boxes carefully to see that they match what was given above.
  4. If need be, you can use the Visual Studio debugger.
    1. Begin by looking at the code in the Calc.aspx.vb file. You can do this by double clicking the file in Solution Explorer.
    2. Click in the left gray margin, the one nearest your code, to set a breakpoint at some likely spot where you might want to pause execution so that you can check the values of variables, etc. The breakpoint will show as a red circle. You can set more than one of these if you like. If you get one in the wrong spot, click on the circle to remove it.
    3. Use Debug, Start Debugging.
    4. You might be asked to modify your web.config file to allow debugging. Do so by changing to debug="true" in the compilation tag. However, if you were to put this web app into production use you should then turn debugging off in web.config so that you don't give away to attackers important information about your code.
    5. Your web app will start locally.
    6. In the resulting browser window, fill in some quantities and click the buttons as before.
    7. The web app will run until it reaches the first breakpoint.
    8. Note that an Autos window will show automatically the values of the most relevant data items in this section of the code.
    9. Use Debug, Step Over (or the equivalent button) to execute the current line of code (the one at the breakpoint) and then pause.
    10. You can then examine the values in the Autos window to see if they are correct.
    11. Repeatedly use Debug, Step Over until you hit the next breakpoint or reach the end of the code. If you want to quickly get to the next breakpoint or the end, you can use the Continue button.
    12. Use Debug, Stop Debugging to turn off the debugging session.
  5. Once you have your app working, be sure to save all of your files in Visual Studio.

Adding Exception Handling

  1. The calculator app will crash if you try to do arithmetic with the empty string in the x or y text boxes.
  2. Use a try...catch block to catch any such exception in the click handler for each of the 5 arithmetic buttons.
  3. Note that the buttons that transfer the answer to one of the other text boxes will work fine even if they are copying the empty string, so they do not need try...catch blocks.
  4. Below is the revised code for the add button click handler. The others are quite similar.

Protected Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
        AnswerTextBox.Text = myCalc.Add(Convert.ToDouble(xTextBox.Text), Convert.ToDouble(yTextBox.Text)).ToString()
    Catch ex As Exception
        AnswerTextBox.Text = "Invalid"
    End Try
End Sub

Using External CSS

  1. Let's add an external style sheet that defines a color scheme for our calculator app.
  2. This is better than setting the color properties of each control on the form, as that would be time-consuming to change at some later date when we need to adjust the color scheme. Editing a CSS file is a lot simpler.
  3. We will change the calculator app so that it looks like this picture.
  4. We will use the following CSS:

        color: #0066FF;
        background-color: #99FF99;
        color: #BB0000;
        background-color: #E0E0E0;

  5. Although we could create a new style sheet and type in the above style information, there is an easier way.
  6. With your form in Design View, select Format, New Style.
  7. You will be given a CSS selector name such as .newStyle1, which is fine.
  8. Use the "Define in" dropdown to select "New style sheet". This will produce an external style sheet, probably named StyleSheet.css.
  9. In the dialog box you can then define your style information. Under the Font category, select a blue color such as the #0066FF suggested above. Note that you can type in the #0066FF or click on a desired color.
  10. Similarly, under the Background category, pick a light green color such as #99FF99 for background-color.
  11. There are many other style choices that can be made, but this is enough for our example.
  12. When you click OK to close the dialog box for building a style you will be asked whether to attach your style sheet. Say yes so that Visual Studio adds a line to the head section of your Calc.aspx web page so that there is a link to the new CSS file.
  13. Save all of your files so that all of them are up-to-date before trying the next item.
  14. Use the mouse to highlight only the div section of your Calc.aspx file (in source view). That is, drag the mouse from the opening angle bracket of the div tag through the ending angle bracket of the closing</div> tag. Do not select anything beyond this, not even blank space, as we want to apply our new CSS style to the div section.
  15. Select View, Apply Styles.
  16. In the dropdown next to .newStyle1 select Apply Style.
  17. You can then close the Apply Style tool.
  18. However, we want different colors for the buttons, so while you have Calc.aspx as the active window, select Format, New Style.
  19. This time change the default selector name (probably .newStyle2) to .buttonStyle, as that will remind us of its purpose.
  20. Use the "Define in" dropdown to select "Existing style sheet".
  21. If not already shown, change the URL box to the name of your CSS file above, probably StyleSheet.css.
  22. Under the Font category, select a red color such as the #BB0000 suggested above.
  23. Under the Background category, use a light gray color such as the #E0E0E0 above as background-color.
  24. Click OK.
  25. Next, apply the new style to the buttons as follows.
  26. Control-click on each of the 7 buttons of Calc.aspx (while in Design view) so that all of the buttons are selected.
  27. Click on View, Apply Styles.
  28. In the pull-down next to .buttonStyle, select Apply Style.
  29. You can now close the Apply Styles tool.
  30. Save all of your files and select Build, Build Web Site.
  31. Click the little green triangle to run your application in a browser. Make sure that the desired styles are showing.
  32. Since we left Web.config with debugging turned on, you might want to change Web.config so that it uses debug="false", then save all files and then run your calculator app without debugging.

Production Use of the App

  1. Does your calculator now work using the live web server instead of just running on your local PC?
  2. Use a URL that begins with the symbolic name (or IP address) of your web server, followed by your username (so as to reach your W drive via the web server), followed by the path to get to the right folder for the calculator, followed by the name of the main page (which you can omit if it is called Default.aspx.)
  3. At Saint Vincent College, check your W drive to see what folder(s) need to be opened to get to your web app. That will help you get the path part of the URL right. The resulting URL might look something like, where you replace YourUserName by your actual user name.

Back to the main page for ASP.NET 4.5 Web Apps

Author: Br. David Carlson
Last updated: September 05, 2017