TECH TIPS Headline Animator

Sunday, December 12, 2010

Simple Calculator through vb.net

This is a post i have made by which one can generate a simple calculator in visual basic.net as shown below




[sourcecode language='vb']
Public Class Form1
Dim dot As Boolean
Dim temp As Double
Dim op As Char
Dim add As Boolean


' Handles buttons 1-9
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click, Button3.Click, Button1.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button14.Click, Button15.Click
If sender.text = "." And dot = True Then Exit Sub
If (sender.text = ".") Then
dot = True
End If


If (add = True) Then
temp = Val(TextBox1.Text)
TextBox1.Text = ""
add = False
End If

TextBox1.Text = TextBox1.Text & sender.text
TextBox1.ForeColor = Color.Black
End Sub

'Clear button
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
TextBox1.Text = ""
temp = 0
End Sub

' Delete button
Private Sub Button16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button16.Click
Dim i, len As Integer
Dim str As String
str = TextBox1.Text
TextBox1.Text = ""
len = str.Length
For i = 0 To (len - 2)
TextBox1.Text = TextBox1.Text & str.Chars(i)
Next
End Sub

'Handles buttons +,-,/,*
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click, Button11.Click, Button12.Click, Button18.Click
If op <> "" Then Button17_Click(sender.text, e)
op = sender.text
add = True
End Sub

'= Answer button
Private Sub Button17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button17.Click
If op = "+" Then
temp = Val(temp) + Val(TextBox1.Text)
add = True
TextBox1.Text = temp
TextBox1.ForeColor = Color.Red
ElseIf op = "-" Then
temp = Val(temp) - Val(TextBox1.Text)
add = True
TextBox1.Text = temp
TextBox1.ForeColor = Color.Red
ElseIf op = "*" Then
temp = Val(temp) * Val(TextBox1.Text)
add = True
TextBox1.Text = temp
TextBox1.ForeColor = Color.Red
ElseIf op = "/" Then
temp = Val(temp) / Val(TextBox1.Text)
add = True
TextBox1.Text = temp
TextBox1.ForeColor = Color.Red
End If
temp = 0
op = ""
End Sub

'% percentage button
Private Sub Button19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button19.Click
TextBox1.Text = Val(TextBox1.Text) / 100
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
op = ""
add = False
End Sub
End Class
[/sourcecode]

Download code here

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More