Monday, September 10, 2012

Simple Calculator tutorial Part 1 of 2 - Visual C# - Windows forms applications

If you're a beginner in programming with Visual C#, then I think this tutorial is very helpful for you.

So we're going to create a very simple calculator, you'll see how much easy it is.
Our target is to create a working calculator similar to this one:

Simple Calculator tutorial

In this part of tutorial we'll build the design of the application.

Open Visual Studio, select "New Project", choose "Visual C#" (you may find it in the Other languages listing), select Windows Forms Application, choose a suitable name like Easy-Calculator.

Edit Form1 Properties. 
  • Size: "300; 240".
  • BackColor: "GradientInactiveCaption", I like this color.
  • MaximumSize: "300; 240", not allowing user to increase the size of the our form.
  • MinimumSize: "300; 240", the minimum size of the form set to its actual size.
  • MaximizeBox: "False", this is important to add so the user don't click the Maximize button.
  • Text: "Easy Calculator", or anything you want.
Add a TextBox from the ToolBox list, and change its properties as following:
  • Dock: "Top", this will place it in the top of the form.
  • Font: "Tahoma; 18pt", making numbers a little bigger. 
  • BackColor: "GradientInactiveCaption", same as the form background color.
  • ReadOnly: "True", since we don't the user to edit the TextBox with his keyboard. 
  • Text: "0".
Add a TableLayoutPanel.
  • We'll place our buttons in this panel. 
  • Change the Dock property to "Bottom".
  • Cick on the upper right corner arrow to show the TableLayoutPanel Tasks, check the picture below.

Simple Calculator tutorial
Click on Edit Rows and Columns...

We need to have 4 Rows and 5 Columns, let the percent value to every row be 20%, and 25% for columns.

Simple Calculator tutorial
Simple Calculator tutorial

Click OK, now extend the TableLayoutPanel height. the results should be like this:

Simple Calculator tutorial

Adding buttons
  • Drag and drop a button to the cell 0,0 (The first row and the first column). Change its Dock property to Fill. Select it and press Ctrl+C. Now press 19 times  Ctrl+V. you should get this:
    Simple Calculator tutorial
  • Remove the following buttons: button17,button10,button15,button20.
  • Set the RowSpan property for button16 to 2, and set the ColumnSpan property for button5 to 4.
  • Finally edit the text property so finally you get this result:
    Simple Calculator tutorial
Save your project so we can continue the next time the programming part, believe me, you'll find it easier than the design. if you have any question Leave a comment and I'll help you. See you next time.