Skip to content

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

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 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.

  • The default code generated in MainWindow.xaml
<Window x:Class="CurrencyConverter_API.MainWindow"
        xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
        xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
        xmlns:d="<http://schemas.microsoft.com/expression/blend/2008>"
        xmlns:mc="<http://schemas.openxmlformats.org/markup-compatibility/2006>"
        xmlns:local="clr-namespace:CurrencyConverter_API"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        
    </Grid>
</Window>

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

<Window x:Class="CurrencyConverter_API.MainWindow"
        xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
        xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
        xmlns:d="<http://schemas.microsoft.com/expression/blend/2008>"
        xmlns:mc="<http://schemas.openxmlformats.org/markup-compatibility/2006>"
        xmlns:local="clr-namespace:CurrencyConverter_API"
        mc:Ignorable="d"
        Title="Currency Converter" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Icon="Images/money.png">
    <Grid>
        
    </Grid>
</Window>
  • Add the below code between the <Grid></Grid> tag.
<Grid.RowDefinitions>
    <RowDefinition Height="60"></RowDefinition>
    <RowDefinition Height="80"></RowDefinition>
    <RowDefinition Height="150"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    <RowDefinition Height="150"></RowDefinition>
</Grid.RowDefinitions>

Now, I have explained to you about the usage of Grid PanelBorder 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:

<Border Grid.Row="2" Width="800" CornerRadius="10" BorderThickness="5">
    <Border.BorderBrush>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
            <GradientStop Color="#ec2075" Offset="0.0" />
            <GradientStop Color="#f33944" Offset="0.50" />
        </LinearGradientBrush>
    </Border.BorderBrush>
    <Rectangle Grid.Row="2">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0" />
                <GradientStop Color="#f33944" Offset="0.50" />
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>
</Border>
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center">
    <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Converter" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Center" Height="80" Width="1000">
    <Label Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Converted Currency" FontSize="20"></Label>
    <Label Name="lblCurrency" Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="20"></Label>
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="60" Width="800">
    <Label Height="40" Width="150" Content="Enter Amount : " Margin="35 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
    <Label Height="40" Width="150" Content="From : " Margin="110 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
    <Label Height="40" Width="150" Content="To : " Margin="130 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Height="90" Width="800" VerticalAlignment="Bottom">
    <TextBox Name="txtCurrency" Width="200" Height="30" Margin="40 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
    <ComboBox Name="cmbFromCurrency" Width="170" Height="30" Margin="60 0 40 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxDropDownHeight="150"></ComboBox>
    <fa:ImageAwesome Icon="Exchange" Height="30" Width="30" Foreground="White" VerticalAlignment="Top"></fa:ImageAwesome>
    <ComboBox Name="cmbToCurrency" Width="170" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxDropDownHeight="150"></ComboBox>
</StackPanel>
<StackPanel Grid.Row="3" Height="100" Width="1000" Orientation="Horizontal">
    <Button Name="Convert" Height="40" Width="150" Content="Convert" Click="Convert_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
        <Button.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0"/>
                <GradientStop Color="#f33944" Offset="0.5"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button Name="Clear" Height="40" Width="150" Content="Clear" Click="Clear_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
        <Button.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0"/>
                <GradientStop Color="#f33944" Offset="0.5"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
</StackPanel>
<StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
    <Image Height="150" Width="150" Source="Images\\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
</StackPanel>

App.xaml page

<Style x:Key="ButtonRound" TargetType="Button">
    <Setter Property="Background" Value="AliceBlue"></Setter>
    <Setter Property="Foreground" Value="White"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="5" Background="{TemplateBinding Background}" BorderThickness="0.5">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Final code of MainWindow.xaml

<Window x:Class="CurrencyConverter_API.MainWindow"
        xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
        xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
        xmlns:d="<http://schemas.microsoft.com/expression/blend/2008>"
        xmlns:mc="<http://schemas.openxmlformats.org/markup-compatibility/2006>"
        xmlns:local="clr-namespace:CurrencyConverter_API"
        xmlns:fa="<http://schemas.fontawesome.io/icons/>"
        mc:Ignorable="d"
        Title="Currency Converter" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Icon="Images/money.png">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60"></RowDefinition>
            <RowDefinition Height="80"></RowDefinition>
            <RowDefinition Height="150"></RowDefinition>
            <RowDefinition Height="100"></RowDefinition>
            <RowDefinition Height="150"></RowDefinition>
        </Grid.RowDefinitions>
        <Border Grid.Row="2" Width="800" CornerRadius="10" BorderThickness="5">
            <Border.BorderBrush>
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                    <GradientStop Color="#ec2075" Offset="0.0" />
                    <GradientStop Color="#f33944" Offset="0.50" />
                </LinearGradientBrush>
            </Border.BorderBrush>
            <Rectangle Grid.Row="2">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0" />
                        <GradientStop Color="#f33944" Offset="0.50" />
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Border>
 
 
        <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center">
            <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Converter" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
        </StackPanel>
        <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Center" Height="80" Width="1000">
            <Label Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Converted Currency" FontSize="20"></Label>
            <Label Name="lblCurrency" Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="20"></Label>
        </StackPanel>
        <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="60" Width="800">
            <Label Height="40" Width="150" Content="Enter Amount : " Margin="35 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
            <Label Height="40" Width="150" Content="From : " Margin="110 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
            <Label Height="40" Width="150" Content="To : " Margin="130 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
        </StackPanel>
        <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Height="90" Width="800" VerticalAlignment="Bottom">
            <TextBox Name="txtCurrency" Width="200" Height="30" Margin="40 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
            <ComboBox Name="cmbFromCurrency" Width="170" Height="30" Margin="60 0 40 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxDropDownHeight="150"></ComboBox>
            <fa:ImageAwesome Icon="Exchange" Height="30" Width="30" Foreground="White" VerticalAlignment="Top"></fa:ImageAwesome>
            <ComboBox Name="cmbToCurrency" Width="170" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxDropDownHeight="150"></ComboBox>
        </StackPanel>
        <StackPanel Grid.Row="3" Height="100" Width="1000" Orientation="Horizontal">
            <Button Name="Convert" Height="40" Width="150" Content="Convert" Click="Convert_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                <Button.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0"/>
                        <GradientStop Color="#f33944" Offset="0.5"/>
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
            <Button Name="Clear" Height="40" Width="150" Content="Clear" Click="Clear_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                <Button.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0"/>
                        <GradientStop Color="#f33944" Offset="0.5"/>
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
        </StackPanel>
        <StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
            <Image Height="150" Width="150" Source="Images\\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
        </StackPanel>
    </Grid>
</Window>

Main part of the Application core part

  • The default code added in MainWindow.xaml.cs is as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace CurrencyConverter_API
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

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.

using System.Windows;
 
namespace CurrencyConverter_API
{
    public partial class MainWindow: Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Add the Model Class:

  • The class matches the data model used in the Web API project.
  • Add the following class to the application:
//Root class is the main class. API return rates in the rates. It returns all currency name with value.
public class Root      
{
    //Get all record in rates and set in rate class as currency name wise
    public Rate rates { get; set; } 
}
 
//Make sure API return value that name and where you want to store that name are the same. Like in API, get response INR, then set it with INR name.
public class Rate   
{
    public double INR { get; set; }
    public double JPY { get; set; }
    public double USD { get; set; }
    public double NZD { get; set; }
    public double EUR { get; set; }
    public double CAD { get; set; }
    public double ISK { get; set; }
    public double PHP { get; set; }
    public double DKK { get; set; }
    public double CZK { get; set; }
}
  • Create an object for root class
//Create an object of Root class 
Root val = new Root();

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.
private async void GetValue()
{
    val = await GetDataGetMethod<Root>("<https://openexchangerates.org/api/latest.json?app_id=69cb235f2fe74f03baeec270066587cf>");
    BindCurrency();
}

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:

public static async Task<Root> GetDataGetMethod<T>(string url)
{
    var ss = new Root();
    try
    {
        using (var client = new HttpClient())
        {
            client.Timeout = TimeSpan.FromMinutes(1);
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var ResponceString = await response.Content.ReadAsStringAsync();
                var ResponceObject = JsonConvert.DeserializeObject<Root>(ResponceString);
                return ResponceObject;
            }
            return ss;
        }
    }
    catch
    {
        return ss;
    }
}

Bind Currency From and To Combobox

Create a private method as BindCurrency().

private void BindCurrency()
{
 
}

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:

DataTable dt = new DataTable();
  • 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.
//Add display column in DataTable
dt.Columns.Add("Text");          
 
//Add Value Column in DataTable
dt.Columns.Add("Rate");             
 
//Add rows in Datatable with text and value. set a value which are fetched from API
dt.Rows.Add("--SELECT--", 0);
dt.Rows.Add("INR", val.rates.INR);
dt.Rows.Add("USD", val.rates.USD);
dt.Rows.Add("NZD", val.rates.NZD);
dt.Rows.Add("JPY", val.rates.JPY);
dt.Rows.Add("EUR", val.rates.EUR);
dt.Rows.Add("CAD", val.rates.CAD);
dt.Rows.Add("ISK", val.rates.ISK);
dt.Rows.Add("PHP", val.rates.PHP);
dt.Rows.Add("DKK", val.rates.DKK);
dt.Rows.Add("CZK", val.rates.CZK);
  • 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.
//Datatable data assign From currency Combobox
cmbFromCurrency.ItemsSource = dt.DefaultView;   
 
//DisplayMemberPath property is used to display data in Combobox
cmbFromCurrency.DisplayMemberPath = "Text";     
 
//SelectedValuePath property is used for set value in Combobox
cmbFromCurrency.SelectedValuePath = "Rate";     
 
//SelectedIndex property is used to bind Combobox it's default selected item is first
cmbFromCurrency.SelectedIndex = 0;         
 
//All property set to To Currency Combobox as From Currency Combobox
cmbToCurrency.ItemsSource = dt.DefaultView;
cmbToCurrency.DisplayMemberPath = "Text";
cmbToCurrency.SelectedValuePath = "Rate";
cmbToCurrency.SelectedIndex = 0;
  • 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 .
//ClearControls used to clear all controls input which user entered
private void ClearControls()
{
    txtCurrency.Text = string.Empty;
    if (cmbFromCurrency.Items.Count > 0)
        cmbFromCurrency.SelectedIndex = 0;
    if (cmbToCurrency.Items.Count > 0)
        cmbToCurrency.SelectedIndex = 0;
    lblCurrency.Content = "";
    txtCurrency.Focus();
}
  • 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.
//Allow only integer in textbox
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
   //Regular Expression to add regex. Add library using System.Text.RegularExpressions;
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}
  • 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

//Convert button click event
private void Convert_Click(object sender, RoutedEventArgs e)
{
 
}
  • Assign the Convert button click event. While clicking on the convert button below code will be executed.
//Declare ConvertedValue with double data type to store currency converted value
double ConvertedValue;
 
//Check if amount textbox is Null or Blank
if (txtCurrency.Text == null || txtCurrency.Text.Trim() == "")
{
    //If amount textbox is Null or Blank then show this message box
	MessageBox.Show("Please Enter Currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    
	//After clicking on the Messagebox's OK button set the focus on amount textbox
	txtCurrency.Focus();        
    return;
}
 
//Else if currency From is not selected or default text as --SELECT--
else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0 || cmbFromCurrency.Text == "--SELECT--")
{
    //Then show this message box
	MessageBox.Show("Please Select Currency From", "Information", MessageBoxButton.OK, MessageBoxImage.Information);       
    //Set the focus to From Combobox
	cmbFromCurrency.Focus();        
    return;
}
//else if currency To is not Selected or default text as --SELECT--
else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0 || cmbToCurrency.Text == "--SELECT--")     
{
    //Then show this message box
    MessageBox.Show("Please Select Currency To", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    
	//Set the focus on To Combobox
	cmbToCurrency.Focus();      
    return;
}
  • 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.”
//If From and To Combobox selects the same value
if (cmbFromCurrency.Text == cmbToCurrency.Text)
{
    //Amount textbox value is set in ConvertedValue. double.parse is used to change datatype String To Double. Textbox text have string and ConvertedValue is double datatype
	ConvertedValue = double.Parse(txtCurrency.Text);        
    
	//Show the label as converted currency and converted currency name. and ToString("N3") is used to placed 000 after the dot(.)
	lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
else
{
    //Calculation for currency converter is From currency value multiplied(*) with amount textbox value and then that total divided(/) with To currency value.
	ConvertedValue = (double.Parse(cmbToCurrency.SelectedValue.ToString()) * double.Parse(txtCurrency.Text)) / double.Parse(cmbFromCurrency.SelectedValue.ToString()); 
    
	//Show the label converted currency and converted currency name.
	lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
  • 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.
//Clear button click event
private void Clear_Click(object sender, RoutedEventArgs e)
{
   //ClearControls method for clear all control value
    ClearControls();
}
  • 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

using System.Windows;
using System.Windows.Input;
using System.Text.RegularExpressions;
using System.Data;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
 
namespace CurrencyConverter_API
{
    public partial class MainWindow : Window
    {
        //Create an object of root class
		Root val = new Root();
 
        //Root class is a main class. API return rates in a rates it return all currency name with Value.
		public class Root
        {
            //Get all record in rates and set in Rate class as currency name wise
			public Rate rates { get; set; }
        }
        
		//Make sure API return value that name and where you want to store that name are same. Like in API get response INR then set it with INR name.
		public class Rate
        {
            public double INR { get; set; }
            public double JPY { get; set; }
            public double USD { get; set; }
            public double NZD { get; set; }
            public double EUR { get; set; }
            public double CAD { get; set; }
            public double ISK { get; set; }
            public double PHP { get; set; }
            public double DKK { get; set; }
            public double CZK { get; set; }
        }
 
        public MainWindow()
        {
            InitializeComponent();
            ClearControls();
            GetValue();
        }
 
        private async void GetValue()
        {
            val = await GetDataGetMethod<Root>("<https://openexchangerates.org/api/latest.json?app_id=69cb235f2fe74f03baeec270066587cf>"); //API Link
            BindCurrency();
        }
 
        public static async Task<Root> GetDataGetMethod<T>(string url)
        {
            var ss = new Root();
            try
            {
                //HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL.
				using (var client = new HttpClient())
                {
                    //The timespan to wait before the request times out.
					client.Timeout = TimeSpan.FromMinutes(1);
                    
					//HttpResponseMessage is a way of returning a message/data from your action.
					HttpResponseMessage response = await client.GetAsync(url);
                    
					//Check API response status code ok
					if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        //Serialize the HTTP content to a string as an asynchronous operation.
						var ResponceString = await response.Content.ReadAsStringAsync();
						
						
						//JsonConvert.DeserializeObject to deserialize Json to a C#
                        var ResponceObject = JsonConvert.DeserializeObject<Root>(ResponceString);   
                        return ResponceObject;  //Return API responce
                    }
                    return ss;
                }
            }
            catch
            {
                return ss;
            }
        }
 
        #region Bind Currency From and To Combobox
        private void BindCurrency()
        {
            //Create an object Datatable
			DataTable dt = new DataTable();
			
			//Add display column in DataTable
            dt.Columns.Add("Text"); 
            
			//Add value column in DataTable
            dt.Columns.Add("Rate");
 
           //Add rows in Datatable with text and value. Set a value which fetch from API
            dt.Rows.Add("--SELECT--", 0);       
            dt.Rows.Add("INR", val.rates.INR);
            dt.Rows.Add("USD", val.rates.USD);
            dt.Rows.Add("NZD", val.rates.NZD);
            dt.Rows.Add("JPY", val.rates.JPY);
            dt.Rows.Add("EUR", val.rates.EUR);
            dt.Rows.Add("CAD", val.rates.CAD);
            dt.Rows.Add("ISK", val.rates.ISK);
            dt.Rows.Add("PHP", val.rates.PHP);
            dt.Rows.Add("DKK", val.rates.DKK);
            dt.Rows.Add("CZK", val.rates.CZK);
 
            //Datatable data assign From currency Combobox
            cmbFromCurrency.ItemsSource = dt.DefaultView;  
			
			//DisplayMemberPath property is used to display data in Combobox
            cmbFromCurrency.DisplayMemberPath = "Text";     
            
			//SelectedValuePath property is used to set value in Combobox
			cmbFromCurrency.SelectedValuePath = "Rate";
			
			//SelectedIndex property is used for when bind Combobox it's default selected item is first
            cmbFromCurrency.SelectedIndex = 0;
 
            //All Property Set For To Currency Combobox As From Currency Combobox
            cmbToCurrency.ItemsSource = dt.DefaultView;
            cmbToCurrency.DisplayMemberPath = "Text";
            cmbToCurrency.SelectedValuePath = "Rate";
            cmbToCurrency.SelectedIndex = 0;
        }
        #endregion
 
        #region Extra Events
        
		//ClearControls used for clear all controls input which user entered
		private void ClearControls()
        {
            txtCurrency.Text = string.Empty;
            if (cmbFromCurrency.Items.Count > 0)
                cmbFromCurrency.SelectedIndex = 0;
            if (cmbToCurrency.Items.Count > 0)
                cmbToCurrency.SelectedIndex = 0;
            lblCurrency.Content = "";
            txtCurrency.Focus();
        }
 
        
		//Allow only integer in textbox
		private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }
        #endregion
 
        #region Button Click Event
        
		//Assign convert button click event
		private void Convert_Click(object sender, RoutedEventArgs e)
        {
            //Declare ConvertedValue with double DataType for store currency converted value
			double ConvertedValue;
            
			//Check amount textbox is Null or Blank
			if (txtCurrency.Text == null || txtCurrency.Text.Trim() == "")      
            {
                //If amount textbox is Null or Blank then show this message box
				MessageBox.Show("Please Enter Currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);  
                
				//After click on Messagebox OK set focus on amount textbox
				txtCurrency.Focus();        
                return;
            }
            //Else if currency From is not selected or default text --SELECT--
			else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0 || cmbFromCurrency.Text == "--SELECT--")       
            {
                //Then show message box
				MessageBox.Show("Please Select Currency From", "Information", MessageBoxButton.OK, MessageBoxImage.Information);        
                
				//Set focus on From Combobox
				cmbFromCurrency.Focus();        
                return;
            }
            //Else if currency To is not selected or default text --SELECT--
			else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0 || cmbToCurrency.Text == "--SELECT--")
            {
                //Then show message
				MessageBox.Show("Please Select Currency To", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                
				//Set focus on To Combobox
				cmbToCurrency.Focus();      
                return;
            }
 
            //If From and To Combobox selects same value
			if (cmbFromCurrency.Text == cmbToCurrency.Text)     
            {
                //Amount textbox value set in ConvertedValue. double.parse is used to change Datatype String To Double. Textbox text have String and ConvertedValue is double datatype
				ConvertedValue = double.Parse(txtCurrency.Text);        
                
				//Show in label converted currency and converted currency name. And ToString("N3") is used for placing 000 after dot(.)
				lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");     
            }
            else
            {
                //Calculation for currency converter is From currency value is multiplied(*) with amount textbox value and then that total is divided(/) with To currency value.                
				ConvertedValue = (double.Parse(cmbToCurrency.SelectedValue.ToString()) * double.Parse(txtCurrency.Text)) / double.Parse(cmbFromCurrency.SelectedValue.ToString());      
                
				//Show the label converted currency and converted currency name.
				lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");     
            }
        }
 
        //Assign a clear button click event
		private void Clear_Click(object sender, RoutedEventArgs e)
        {
            //ClearControls method is used to clear all control values
			ClearControls();    
        }
        #endregion
    }
}

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.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide