Develop a Currency Converter in the .NET Compact Framework

Develop a Currency Converter in the .NET Compact Framework

he best way to learn how to use the various controls in the .NET Compact Framework (CF) is to actually use them. So starting with this article, I will demonstrate a few techniques you can use to develop applications for Pocket PC devices using Visual Studio .NET 2003.

In this first part of the series, I will show how you can develop a simple currency converter using .NET CF’s built-in controls. To do this, I will develop a Pocket PC application that allows a user to convert currencies from one country to another. For the sake of simplification, the sample application is limited to three currencies: U.S., RMB (Renminbi, Chinese currency), and Singapore.

Populating the Form with Controls
In Visual Studio.NET 2003, create a new Smart Device Application (Microsoft’s term for a mobile application that runs on the Pocket PC platform as well as on Windows CE .NET). Your project should open with the default Form1 ready for input. Populate it with the controls as shown in Figure 1, beginning with the “Conversion” TabPage on the right. The controls used in this example are:

Figure 1. Setting Up the Form. Populate the default Form1 with the various controls you’ll need on each of two different TabPages.
  • Label
  • Textbox
  • ComboBox
  • Button
  • MenuItem
  • TabControl
  • ListBox

The first Tab page (“Conversion”) contains two ComboBox controls for the user to select the currencies to convert. Once the currencies are selected, the user can click on the Button controls to input the amount to convert. The BackSpace button is to delete the last character entered while the Clear button clears the entire line of digits as displayed in the TextBox control. The ListBox control contains a list of previous conversions.

Figure 2. Clear History. Adding the MenuItem control to the MainMenu to allow the user to start the application anew.

In the second tab page (“Set Rates”), the user can set the exchange rate for each currency using the ComboBox and TextBox controls.

Besides adding the various controls, also add a MenuItem control to the MainMenu control, as shown in Figure 2. When the user selects the Clear History menu item, it clears the ListBox control in the first tab page.

Setting Up Tab Controls
For the UI of this application, I want the user to be able to move between two different forms, which are layered behind one another. The TabControl lets me create a file tab metaphor so that only one form is visible and active at any time. My application contains one TabControl control, which in turn contains two TabPage controls. The first TabPage is called “Conversion” while the second is “Set Rates.” The TabPage control is maximizes the available screen real estate.

The first “tab” of the application is the default Form1. To add a second TabPage control to a form, select the TabControl control and in the Properties window, click on the Add Tab link, as shown in Figure 3. You can set as many TabPages as you like in your own applications.

Figure 3. Add a New TabPage Control. You’ll need to master building TabPages to write sophisticated applications for handheld devices.

Coding the Controls
Now that the forms are set up, we need to begin writing the application logic that will perform the currency translation. Because our sample application deals with three currencies, we need three dataset objects to bind the exchange rate of each currency to the ComboBox controls, where the end users selects the currencies to convert. To do this, switch to code view and declare the following three dataset objects and a global variable.

    Dim ds0 As New DataSet    Dim ds1 As New DataSet    Dim ds2 As New DataSet    Dim ready As Boolean = False

Now, I need to tell the application where to get the exchange rate information. I have created an XML file, Rates.xml, which contains the exchange rate for each currency. I’ll define a constant for storing this filename.

    Const FILENAME = "My DocumentsPersonalRates.xml"

When the form is first loaded, you need to load the exchange rates by calling the LoadRates() method. After that, bind the dataset objects to the three ComboBox controls.

    Private Sub Form1_Load(ByVal sender As Object, _                           ByVal e As System.EventArgs) _                           Handles MyBase.Load        LoadRates(ds0)        LoadRates(ds1)        LoadRates(ds2)        DoBinding(ComboBox1, ds0)        DoBinding(ComboBox2, ds1)        DoBinding(ComboBox3, ds2)        ready = True    End Sub

The LoadRates() method tries to load the exchanges rate information from the file, Rates.xml, shown here:

         US      1            RMB      8            SIN      1.74   

The base currency is the U.S. dollar. All other currencies are exchanged relative to the U.S. dollars. For example, $1 U.S. is equivalent to 1.74 Singapore dollars.

If the file does not exist when the application is first loaded, the InitRates() method will load the default exchange rates (for simplicity I am assuming that the values are hard coded; in real life these values should preferably be loaded dynamically, say from a Web service).

    Public Sub LoadRates(ByVal ds As DataSet)        Try            ds.ReadXml(FILENAME)        Catch err As Exception            InitRates(ds)  ' init the rates if rates.xml                            ' cannot be found        End Try    End Sub

The InitRates() method creates a dataset containing the Currency table and three default exchange rates. The information is then written to file:

    Public Sub InitRates(ByVal ds As DataSet)        ds.Tables.Add("Currency")        ds.Tables("Currency").Columns.Add("Sym")        ds.Tables("Currency").Columns.Add("Rate")        Dim row As DataRow        row = ds.Tables("Currency").NewRow        row("Sym") = "US"        row("Rate") = 1        ds.Tables("Currency").Rows.Add(row)        row = ds.Tables("Currency").NewRow        row("Sym") = "RMB"        row("Rate") = 8        ds.Tables("Currency").Rows.Add(row)        row = ds.Tables("Currency").NewRow        row("Sym") = "SIN"        row("Rate") = 1.74        ds.Tables("Currency").Rows.Add(row)        ds.WriteXml(FILENAME)    End Sub

The DoBinding() method binds the ComboBox control with the dataset.

    Public Sub DoBinding(ByVal control As _                         System.Windows.Forms.ComboBox, _                         ByVal ds As DataSet)        control.Items.Clear()        control.DataSource = ds.Tables("Currency")        control.DisplayMember = "Sym"        control.ValueMember = "Rate"    End Sub

Accepting Data Entry
Users enter the amount of currency they wish to convert using the buttons 0 to 9 on the first TabPage, which invokes the cmdButtons event. Note that this event is fired whenever one of the 10 buttons is pushed. It must also perform error checking so that users may not enter illegal entries, such as multiple decimal points [.]. Once the button is clicked, the value appends the TextBox control, to show the user what numbers he has entered:

    Private Sub cmdButtons _                (ByVal sender As System.Object, _                 ByVal e As System.EventArgs) _                 Handles cmd0.Click, cmd1.Click, cmd2.Click, _                         cmd3.Click, cmd4.Click, cmd5.Click, _                         cmd6.Click, cmd7.Click, cmd8.Click, _                         cmd9.Click, cmdPt.Click        If txtValue.Text.Length > 7 Or _          (txtValue.Text.IndexOf("0") = 0 And _          CType(sender, Button).Text = "0") Or _          (txtValue.Text.IndexOf(".") >= 0 And _          CType(sender, Button).Text = ".") Then  ' remove                                                   ' multiple "."        Else            If txtValue.Text.IndexOf("0") = 0 Then                txtValue.Text = ""            End If            txtValue.Text += CType(sender, Button).Text        End If    End Sub

When the value in the TextBox control is changed, indicating that the user has entered another number, the conversion amount must be recalculated. The UpdateValue event handles recalculation when any of these events occur:

  • The selection in ComboBox1 is changed.
  • The selection in ComboBox2 is changed.
  • The value in the TextBox control is changed.

    Private Sub UpdateValue _               (ByVal sender As System.Object, _                ByVal e As System.EventArgs) _                Handles ComboBox1.SelectedIndexChanged, _                        txtValue.TextChanged, _                        ComboBox2.SelectedIndexChanged        If ready And txtValue.Text <> "" Then            Try                lblResult.Text = CSng(txtValue.Text) * _                                 CSng(ComboBox2.SelectedValue) / _                                 CSng(ComboBox1.SelectedValue)            Catch ex As Exception                'do nothing            End Try        End If    End Sub

The cmdBackSpace_Click() method is fired when the Back Space button is clicked. It is used to remove the last digit that was entered:

    Private Sub cmdBackSpace_Click _               (ByVal sender As System.Object, _                ByVal e As System.EventArgs) _                Handles cmdBackSpace.Click        ' length must be greater than 1 for deleting        If txtValue.Text.Length > 0 Then            txtValue.Text = Mid(txtValue.Text, 1, _                            txtValue.Text.Length - 1)        End If        ' set to 0 if length is zero        If txtValue.Text.Length = 0 Then            txtValue.Text = 0        End If    End Sub

The Clear button resets the TextBox control to the value “0”:

    Private Sub cmdClear_Click _               (ByVal sender As System.Object, _                ByVal e As System.EventArgs) _                Handles cmdClear.Click        txtValue.Text = 0    End Sub

The “=” button adds the current conversion into the ListBox control.

    Private Sub cmdEq_Click _               (ByVal sender As System.Object, _                ByVal e As System.EventArgs) _                Handles cmdEq.Click        Dim str As String        str = txtValue.Text & ComboBox1.Text & " = " _              & lblResult.Text & ComboBox2.Text        ListBox1.Items.Add(str)    End Sub

The Clear History menu item simply clears the items in the ListBox control:

    Private Sub MenuItem2_Click _               (ByVal sender As System.Object, _                ByVal e As System.EventArgs) _                Handles MenuItem2.Click        ListBox1.Items.Clear()    End Sub

The second TabPage control for the sample application allows the user to change the exchange rate of each currency. In production, this would frequently be done via a Web service, which would grab the latest rates. In this case users can override the rates included in the rates.xml file. When ComboBox3 control is selected (see Figure 1), the rate for the respective currency is displayed.

    Private Sub ComboBox3_SelectedIndexChanged _                (ByVal sender As System.Object, _                 ByVal e As System.EventArgs) _                 Handles ComboBox3.SelectedIndexChanged        txtRate.Text = ds2.Tables("Currency").Rows _                       (ComboBox3.SelectedIndex).Item _                       ("Rate").ToString    End Sub

The Update button will cause all the Dataset objects to be updated and reflect the newly entered rate. It will then call the saveRate() method to save the changes to the Rates.xml file.

    Private Sub cmdUpdate_Click _                (ByVal sender As System.Object, _                 ByVal e As System.EventArgs) _                 Handles cmdUpdate.Click        ds0.Tables("Currency").Rows _                  (ComboBox3.SelectedIndex).Item _                  ("Rate") = txtRate.Text        ds1.Tables("Currency").Rows _                  (ComboBox3.SelectedIndex).Item _                  ("Rate") = txtRate.Text        ds2.Tables("Currency").Rows _                  (ComboBox3.SelectedIndex).Item _                  ("Rate") = txtRate.Text        saveRate(ds2)    End Sub
Figure 4. Using the Currency Converter. Users enter the amount to convert and the application retrieves the exchange rate from an XML file to perform the conversion.

Finally, the saveRate() method saves the new exchange rates onto file:

    Public Sub saveRate(ByVal ds As DataSet)        ds.WriteXml(FILENAME)        MsgBox("Rates saved.")    End Sub

That’s it! Press F5 in Visual Studio to run the application. Figure 4 shows the currency converter in action.

A currency converter is just an example of types of things you can do with .NET CF. If a currency converter is not what you need, you can extrapolate the logic and tactics shown in this article in thousands of other ways. For example, you’ve learned:

  • How to use various built-in controls in .NET CF
  • How to use Datasets to manipulate XML documents
  • How to use of XML documents as data storage
  • How to program your controls to handle events

In my next article for DevX, I will show how to build an enhanced file explorer using the TreeView control. It will emulate the Windows Explorer that users are used to in Windows.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted