Geeks With Blogs
Code.Blog Code Talk for the Game Developer

Here's a quick and simple program you can use to learn to convert text to a double, store the double, and return true or false based on the results of the conversion.  First, the form:

Standard Form:

Error Form:

The Code

Here's the complete background code:

Public Class Form1
    Private dTotal As Double
 
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub
 
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        If (Not ConvertToMoney(txtAmount.Text)) Then
            lblError.Visible = True
        Else
            lblError.Visible = False
        End If
 
        lblOutput.Text = FormatCurrency(dTotal)
    End Sub
 
    Private Function ConvertToMoney(ByVal sAmt As String) As Boolean
        Try
            Dim dResult As New Double
            dResult = CDbl(sAmt)
            dTotal += dResult
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lblOutput.Text = FormatCurrency(dTotal)
    End Sub
 
    Private Sub txtAmount_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtAmount.KeyDown
        If (e.KeyValue = Keys.Enter) Then
            btnAdd_Click(sender, e)
        End If
    End Sub
End Class
 
Basically, there's a function you can use to format currency called (oddly enough) FormatCurrency().  All I've done is created a wrapper function that accepts a string, converts it to a double through the use of CDbl(), adds it to a global double total variable, and return true.  If any of that fails, I return false.  Back in the calling method (btnAdd_Click()), I check the result and display my error message if it returns false.  Then I can safely use FormatCurrency() on my total amount.
Code will be up soon.
Posted on Tuesday, August 26, 2008 11:28 AM Tutorials | Back to top


Comments on this post: Code a la Carte: Monetary Conversions In VB

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Matthew Christian | Powered by: GeeksWithBlogs.net