School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,116 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,002 people online right now. Registration is fast and FREE... Join Now!




An Updatable Unit Conversion Calculator

 
Reply to this topicStart new topic

> An Updatable Unit Conversion Calculator, A Unit Conversion calculator which can be updated with additional unit

PDUNZ
Group Icon



post 20 Aug, 2009 - 05:46 AM
Post #1


Features:
Enable easy addition of Units and their conversion factors.
Categories for Units for easy selection - ie Length, Weight, Distance etc.

Step 1
First step is to get some unit conversion factors to put in our datafile. For a start, I am going to
use just a few units.

LB to KG - 1lb = 0.45359237 kilograms.
KG to LB - 1KG = 2.20462262 pounds.
Mile to KM - 1 Mile = 1.609344 kilometers.
KM to Mile - 1KM = 0.621371192 miles.

Ok, now that we have some conversion numbers, lets make a datafile. The datafile will CSV, and contain 3
important values - Category, Unit Name, Unit Conversion Number.

So lets get to it. Create a text file named data.txt in your projects bin/debug directory and add the details for the units as shown - I have also included the Categories so they can be updated as well.

CODE

Category,Weight
Category,Distance
Weight,LB to KG,0.45359237
Weight,KG to LB,2.20462262
Distance,Mile to KM,1.609344
Distance,KM to Mile,0.621371192


I will be using an identifier called "Field", but you can name it anything. With the above, the "Fields" are seperated by a comma. So anything before the first comma is Field 0, then Field 1, and Field 2 - Field0,Field1,Field2.

As you can see, there are 2 categories for the Units we have, Weight and Distance. We will be using these later on to display only the units for that selected category.

Step 2
* Create a new Project, and add 2 combo boxes, 2 textboxes, 4 labels and a button.
* Change the labels to the following, Category, Convert To, Value to Convert, Result.
* Change the Name of one of the Comboboxes to cboCategory, and place next to the label "Category".
* Change the name of the other Combobox to cbConvertTo, and place next to the label "Convert To".
* Change one textbox name to txtInputVal and place next to the label "Value to Convert".
* And lastly, name the other textbox txtResult and place it next to the "Result" label.
* Give your button text to "Convert"

This is how it should look so far,


Step 3
Under Form Class Form1, add Dim UnitConvVal As Double ' Global Variable for Unit Value.

Step 4
Now to do some coding. First we are going to make a Public Sub called Dataload.

CODE

Public Sub DataLoad(ByVal Switch As String)

End Sub


In the above code I have included "Switch" which will be used for calling DataLoad as shown down below.

Step 5
Next, we will add the following into the sub. This includes the Data Filename, as well determining the seperator in the file.

CODE

Dim tfLines() As String = System.IO.File.ReadAllLines("data.txt") ' File to load.
For Each line As String In tfLines ' Load and read all lines in file.
Dim field As String() = line.Split(","c) ' Split using ,.


Step 6
Now we will add a Select Case for the "Switch".
Start by adding Select Case Switch.

Now we will add the first Case, which will be "LoadCategory". This is run when Form1 is loaded (application start) and fills the Category Combobox with the list of categories from the datafile.

CODE

Case "LoadCategory"
  If field(0) = "Category" Then
     cboCategory.Items.Add(field(1))
     cboCategory.SelectedIndex = 0 ' Auto Select first Category.
  End If


Field(0) is the first "field" in the Datafile, the above code will go though the lines of the data file, and searches for "Category" - and if it finds it, then it adds the second field "Field(1) to cboCategory. Look at the sample datafile at the start and you will see what I mean.

Now after that, and still within the Select Case, add the next part.

CODE

Case "LoadUnits"
  If field(0) = CStr(cboCategory.SelectedItem) Then
    cboConvertTo.Items.Add(field(1))
    cboConvertTo.SelectedIndex = 0 ' Auto Select first Unit.
  End If


This case is "LoadUnits", which is used when a category is selected. This searches the file for the selected category (Weight or Distance) and adds the Units (Field(1)) to cboConvertTo.

Now the last case, "SelectUnit" grabs the conversion value for the select unit from cboConvertTo, and sets it in "UnitConVal".

CODE

Case "SelectUnit"
  If field(1) = CStr(cboConvertTo.SelectedItem) Then
    UnitConvVal = CDbl(field(2)) ' Load Unit's Conversion value, store in UnitConvVal as Double.
  End If


Now we close the Select Cases, and add a "Next" for the loop.

CODE

  End Select
Next


Step 7
Now we will add code to each of the comboboxe's SelectedIndexChanged property, and also for the Calculate button as follows.

Form_Load - Call the Sub DataLoad with the Switch "LoadCategory" when the form loads, and fills the combobox with the Categories.
DataLoad("LoadCategory") ' Switch to DataLoad to load Categories on form load..

cboCategory_SelectedIndexChanged - Calls the Sub DataLoad with the Switch "LoadUnits" when a Category is selected.
CODE

cboConvertTo.Items.Clear() ' Clear cboConvertTo Combobox when re-loading units after selection change.
   DataLoad("LoadUnits")


cboConvertTo_SelectedIndexChanged - Calls the Sub DataLoad with the Switch "SelectUnit" when a Conversion Unit is selected from cboConvertTo.
DataLoad("SelectUnit")

And btnCalculate - First checks to see if anything is entered in txtInputVal, and if there is - proceed to calculate and display the conversion, otherwise show a message box reminding to enter a value.
CODE

If txtInputVal.Text = Nothing Then
    MessageBox.Show("Please Enter A Value to Convert") ' Display message if no value is entered.
Else
    txtResult.Text = CStr(CDbl(txtInputVal.Text) * UnitConvVal) ' If Value has been entered, compute conversion for unit.
End If


Step 8
Now the code that you should end up with is
CODE

Option Strict On
Option Explicit On
Public Class Form1
    Dim UnitConvVal As Double ' Global Variable for Unit Value.

    Public Sub DataLoad(ByVal Switch As String)
        Dim tfLines() As String = System.IO.File.ReadAllLines("data.txt") ' File to load.
        For Each line As String In tfLines ' Load and read all lines in file.
            Dim field As String() = line.Split(","c) ' Split using ,.

            Select Case Switch
                Case "LoadCategory"
                    If field(0) = "Category" Then
                        cboCategory.Items.Add(field(1))
                        cboCategory.SelectedIndex = 0 ' Auto Select first Category.
                    End If

                Case "LoadUnits"
                    If field(0) = CStr(cboCategory.SelectedItem) Then
                        cboConvertTo.Items.Add(field(1))
                        cboConvertTo.SelectedIndex = 0 ' Auto Select first Unit.
                    End If

                Case "SelectUnit"
                    If field(1) = CStr(cboConvertTo.SelectedItem) Then
                        UnitConvVal = CDbl(field(2)) ' Load Unit's Conversion value, store in UnitConvVal as Double.
                    End If
            End Select
        Next

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DataLoad("LoadCategory") ' Switch to DataLoad to load Categories on form load.
    End Sub

    Private Sub cboCategory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategory.SelectedIndexChanged
        cboConvertTo.Items.Clear() ' Clear cboConvertTo Combobox when re-loading units after selection change.
        DataLoad("LoadUnits")
    End Sub

    Private Sub cboConvertTo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboConvertTo.SelectedIndexChanged
        DataLoad("SelectUnit")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
        If txtInputVal.Text = Nothing Then
            MessageBox.Show("Please Enter A Value to Convert") ' Display message if no value is entered.
        Else
            txtResult.Text = CStr(CDbl(txtInputVal.Text) * UnitConvVal) ' If Value has been entered, compute conversion for unit.
        End If
    End Sub
End Class


Now run the program, and if all goes well - the Category combobox should be filled with all the categories (in this case - Weight and Distance). Now select a category and a list of available units should be filled in the next combobox. Next, select a unit to convert, then enter a value in the textbox and click "Convert" - and the result should if all goes well - be displayed in the Results textbox. Try this for each of the categories and units.



As you have noticed, I havn't formated the result which is why there are quite a few decimal places, but you can use something like FormatNumber(CStr(CDbl(txtInputVal.Text) * UnitConvVal), 2).

Now, try adding a new category and a conversion unit to the datafile and see if it shows up in the program.

Thanks for reading.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

PDUNZ
Group Icon



post 20 Aug, 2009 - 04:58 PM
Post #2
Screenshots (Forgot to add them when I transfered sorry).
Attached Image

Attached Image
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 01:23PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month