In this article, you will learn how to create the “Currency Converter” application using WPF in C# with the API. In the previous articles, I have shown you the same but using the static data and database. Now I will show you to build using the API. So, let’s start.

NOTE: In the previous article, “Build a currency converter application using WPF in C# with static data,” I have explained to you everything about the currency converter application and “What is WPF?” etc. Check out the “Build a currency converter application using WPF in C# with static data” article to have a clear idea about this article if you are new to this article.

Step by step guide for building a Currency Converter application using WPF and C# with API

Create a new project

  • Firstly, open Visual Studio and select Create a new project under the Get started menu.
  • Select WPF App (.Net Framework)
  • Click on the Next button.

Configure project

  • Enter the project name as you wish. I am using the naming the project as CurrencyConverter_API.
  • Choose the location where you want to save your project.
  • Click on the Create button.

Then Visual Studio creates the project with some default pages.

  • MainWindow.xaml
  • MainWindow.xaml.cs
  • App.xaml
  • App.config

I have already explained the above files in the previous article,  “Build a currency converter application using WPF in C# with static data.

  • The default code generated in MainWindow.xaml

Designing the application

Now, change the following properties in the XAML code for the NavigationWindow element:

  • First, set the Title property value to “Currency Converter.”
  • Remove default Height and Width from window tag properties and add SizeToContent=” WidthAndHeight” property to set window form according to the content size.
  • Set up WindowStartupLocation property to “CenterScreen” to set the center position of the window.
  • Set up Icon=”Images\money.png” property to set the application’s icon and so will be visible on the title bar.

After making the above changes, the property will look as below

  • Add the below code between the <Grid></Grid> tag.

Now, I have explained to you about the usage of Grid Panel, Border and StackPanel in WPF. If you haven’t checked out, please check out in the previous article,  “Build a currency converter application using WPF in C# with static data.

Let’s add the code for the respective component one by one as below:

App.xaml page

Final code of MainWindow.xaml

Output:

Main part of the Application core part

  • The default code added in MainWindow.xaml.cs is as below:

The namespace is designed to provide a way to keep one set of names separate from another. This class names declared in one namespace does not conflict with the same class names declared in another.

The namespace definition begins with the keyword namespace.

It is a partial class is a special feature of C# which provides a special ability to implement the functionality of a single class into multiple files. When the application is compiled all the files are combined into a single class file.

The partial class is created by using a partial keyword and the keyword is also useful to split the functionality of interfaces, methods, or structure into multiple files.

InitializeComponent() is a method automatically written for you by the Form Designer when you create/change your forms. Now you need to drag controls to the Form in Visual Studio. Behind the scenes, Visual Studio adds code to the InitializeComponent method, which is called in the Form constructor.

Remove unnecessary namespace from our code.

Add the Model Class:

  • The class matches the data model used in the Web API project.
  • Add the following class to the application:
  • Create an object for root class

API Call:

  • The async and await keywords in C# are used in async programming. Asynchronous methods defined using the async keyword are called async methods.
  • Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits, and it takes more time. The application stops responding. With the use of an asynchronous approach, the applications continue with other tasks as well.
  • Here I am using the open exchange rate API. You can get API from https://openexchangerates.org/.
  • After getting the API response successfully, call BindCurrency() method.

Deserialize API:

  • The HTTP client components that allow users to consume modern web services over HTTP. The HTTP components that can be used by both clients and servers. For use, HTTP client add using System.Net.Http namespace.
  • HttpClient is able to process multiple concurrent requests at a time. It supports the async feature of .NET framework. The HttpClient class provides a base class for receiving/sending the HTTP requests/responses from a URL.
  •  It is a layer over the HttpWebRequest and HttpWebResponse. All methods with HttpClient are asynchronous.
  • The use of System.Threading.Tasks namespace provides types that simplify the work of writing asynchronous and concurrent code. The main types are Task which represents an asynchronous operation that can be waited on and canceled, and Task<TResult>, which is a task that can return a value.
  • The using Newtonsoft.Json namespace provides classes that are used to implement the core services of the framework. The default JSON name table implementation. Instructs the JsonSerializer how to serialize the collection.
  • For use of Newtonsoft.Json namespace add a reference. Open solution explorer right click on references. Select add references menu find newtonsoft.json check the checkbox and click on ok button.
  • Add using System namespace for use timespan class.

The following code is used to send a GET request for currency value, as shown below:

Bind Currency From and To Combobox

Create a private method as BindCurrency().

Here:

Private is an access modifier. Type or member can be accessed only by code in the same class or struct.

The Void keyword is used for the method signatures to declare a method that does not return any value. The method declared with the void return type cannot provide any arguments to any return statements they contain.

The BindCurrency() is a name of method.

Create an object of DataTable as below:

  • Import namespace using System.Data on top of the MainWindow.xaml.cs.
  • The DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints.
  • DataTable dtCurrency = new DataTable(); Using this code you are creating an empty data table for which the TableName property is set to dtCurrency. You can use this property to access this data table from a DataTable Collection.
  • In DataTable, add two columns:
    • Text
    • Rate
  • Add some rows with data in the data table. Here I have added currency name in a text column, and in rate column, I add rate from rate class, which are fetched from API.
  • After adding data to the DataTable assign data to the Combobox using the ItemSource Attribute.
  • Set the Combobox DisplayMemberPath Attribute which you want to show in combobox as display text.
  • Set the Combobox SelectedValuePath Attribute which you want to set in combobox as value.
  • Make sure both properties are set with the same as DataTable column name.
  • After adding the BindCurrency() method call it in GetValue() method. Because when the application run GetValue() method get response from API and set in BindCurrency() method .

Output:

  • Create a new method as Clearcontrols().
  • This method will be used to clear all control values which the user entered.
  • Add this method in the MainWindow() method.
  • Create a method NumberValidationTextBox(). This method is used to allow the Amount textbook the use of numbers using a regular expression.
  • Import namespace using System.Text.RegularExpressions on top of the MainWindow.xaml.cs for use regular expression.
  • Import using System.Windows.Input namespace. TextCompositionEventArgs deals with changes while composing a text, so it has many properties dealing with the text and what is explicitly changing.

Calculation of Currency Converter

  • Assign the Convert button click event. While clicking on the convert button below code will be executed.
  • Declare a variable ConvertedValue with the double datatype. It is used to store the converted value and show it in the label.
  • Check validation if the Amount textbox is blank. If so, then it shows the message “please enter amount.”
  • Check validation if the user did not select any currency from FromCurrency Combobox, then it shows the message “Please select currency from.”
  • Check validation if the user did not select any currency from ToCurrency Combobox, then it shows the message “Please select currency to.”
  • Check the condition if the from currency and to currency have the same currency name then store the amount textbox value in the convertedValue variable. e.g., Enter 10 in the Amount textbox, then select in from currency Combobox USD and to currency Combobox USD, then show the currency name with the converted value. e.g., “USD 10.000.”
  • If the from currency and the currency are not the same, then else part will be executed.
  • The from currency value will be multiplied (*) with the amount textbox value and then that total divided(/) to currency value and it’s store in ConvertedValue variable.
  • Display the converted currency name with converted value in the label.
  • Assign a clear button click event.
  • Call the ClearControls() method to clear all controls input which the user entered.

Final code of MainWindow.xaml.cs

Output:

Summary

In this article, you have learned how to create a Currency Converter application using WPF with C# and API. You have used API to get the currency rate and assign currency rate to currency Combobox.