In this article, you will learn how to create a C# Currency Converter using WPF. All you need to have is a good knowledge of C#.
If you are interested in becoming a professional software developer, make sure to check out our courses!
What is a Currency Converter?
A Currency Converter is a WPF application designed to convert one currency into another to check its corresponding value. The program is generally a part of a web site, or it forms a mobile app. It is based on the current market or bank exchange rates.
To convert one currency into another, all you need to do is enter an amount of money (e.g., ‘1000’) and choose the currency and select the monetary value (e.g. “United States Dollar”). You can try with the multiple monetary selections. The application then calculates the entered amount with the exchange value and displays the corresponding amount of money.
What is WPF?
WPF stands for Windows Presentation Foundation. And, the WPF is a UI framework that creates desktop client applications. Also, it is a part of .NET. It supports a broad set of application development features, including resources, an application model, layout, data binding, documents, controls, graphics, and security in terms of the WPF development platform.
The WPF uses Extensible Application Markup Language (XAML) to provide a declarative model for application programming.
Technical Requirements for building a C# Currency Converter
Before moving further, I assume that you must be familiar with below-listed things:
1. Programming basics
To build this application, I will be using the C# language to write the code for the core logic.
The C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp.” Microsoft developed it. C# is widely used for developing web applications and desktop applications.
2. IDE (Integrated development environment)
Visual studio is the best editor for writing code and develop websites, web apps, software, mobile apps.
Click here to download Visual Studio
Step by step guide for building a C# Currency Converter application using WPF
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 of your choice. I am using the project name CurrencyConverter_Static.
- Select the location where you want to save your project.
- Click on the create button.
As you have completed the project creation steps, the Visual Studio creates the project with some default pages.
- MainWindow.xaml
- MainWindow.xaml.cs
- App.xaml
- App.config
- MainWindow.xaml file defines a WPF application and any application resources. You can also use this file to specify the UI. In this case – MainWindow.xaml, it automatically shows when the application starts.
- MainWindow.xaml.cs is a file with a code-behind file that contains code that handles the events declared in MainWindow.xaml, also, the file contains a partial class for the window defined in XAML.
- App.xaml is also the place to subscribe to essential application events, like application start, unhandled exceptions, etc. App.xaml is the declarative starting point of your application. The Code-behind file is called App.xaml.cs. It works a lot like Windows, where the two files are partial classes. They exist together to allow you to work in both markup (XAML) and Code-behind.
- App.config files are XML files that can be changed as per requirement. The administrator can control which protected resources an application can access, which versions of assemblies an application will use, and where remote applications and objects are located. Developers can put settings in configuration files. e.g., the connection string for connecting with the database.
- The default code generated in MainWindow.xaml
<Window x:Class="CurrencyConverter_Static.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_Static"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
Designing the C# Currency Converter 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_Static.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_Static"
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>
- The Grid Panel provides a flexible area which consists of rows and columns also child elements can be arranged in tabular form. The items can be added to any specific row and column by using Grid.Row and Grid.Column properties.
- By default, the Grid panel is created with one row and one column. And, the Multiple rows and columns are created by RowDefinitions and ColumnDefinitions properties.
Borders in WPF works a bit differently. The Border in XAML has its control that can be applied to other controls or XAML elements. For placing a border around an element, WPF provides the Border element, which is similar to other WPF elements. Border has Width, Height, Background, and HorizontalAlignment and VerticalAlignment properties.
<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>
Besides the common properties, the Border has two properties that make Border look like a border, which is BorderThickness and BorderBrush.
BorderBrush is a property that represents the brush that is used to draw the Border. BorderThickness is a property which represents the thickness of the Border.
The Corner Radius is a property used to indicate the degree to which the corners of the border will be rounded. For creating curved borders for the windows, you need to use CornerRadius property of the ChromelessWindow. Also, the default value is zero, which implies sharp corners.
- The linear gradient brush paints an area with a linear gradient. The default value of the linear gradient is diagonal. The StartPoint and EndPoint properties of the LinearGradientBrush represent the start and endpoints of a gradient.
- The gradient stop properties:
- Color – Property to set color is described using a predefined color name or hexadecimal notation.
- OffSet – Offset determines the position of the color between your start and endpoints.
The Rectangle object represents a rectangle shape. Which draws a rectangle with the given height and width. Also, the width and height properties of the rectangle class represent the width and height of a rectangle. And, the Fill property fills the interior of a rectangle.
Now, let’s design the StackPanel.
<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>
- The Stackpanel is a useful and straightforward layout panel in XAML. In the stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the “Orientation” property. Stackpanel is used whenever any list is about to be created.
- Any control in WPF can be placed within a grid by using its Grid.Row and Grid.Column properties that represent which column and which row a control will be placed inside. The values of rows and columns start with 0. That means, if there are five rows in a grid, the first row will be represented by the number 0.
- In the stackpanel tag, add a control that is used in our program. e.g., Label, Textbox, Combobox, Button, Image, etc.
- Set the Controls property as per requirement. e.g., Height, Width, HorizontalAlignment, VerticalAlignment, Margin, FontSize, Foreground, Content, Name, etc.
- Here I used the lblCurrency label to display converted currency name and converted currency value.
- fa:ImageAwesome tag is used to show the icon. To use this control first, you need to add “fontawesome.wpf” to the Library.
- Open solution explorer.
- Right-click on the project name. Select “Manage Nuget Packages.” Select the Browse tab and search for “fontawesome.wpf” and select it and click on the install button.
- Fontawesome gives you scalable vector icons that can instantly be customized.
- The Click attribute of the Button element adds the click event handler. The Click=”Convert_Click” is raised when the Button control is clicked.
- Between the button, tag put <Button.Background> tag. it is used to set the button background color.
- A LinearGradientBrush paint an area with a linear gradient. The linear gradient brush object represents a linear gradient brush. The default value of linear-gradient value is diagonal. The StartPoint and EndPoint properties of the LinearGradientBrush represent the start and endpoints of a gradient.
- The gradient stop properties:
- Color – in this property, you can set a color with a color name or code.
- OffSet – Offset determines the position of the color between your start point and endpoint.
- In the “App.xaml” page, set the property of button border rounded. “App.xaml” page is default created when you create a WPF Project.
- Between the <Application.Resources></Application.Resources> tag you need to add the code below.
- x:key property set name “ButtonRound.” To use this in the button, use Style=”{StaticResource ButtonRound}” property.
- TargetType property sets the target of the controls you want to apply this style to the property.
App.xaml Page
<Style x:Key="ButtonRound" TargetType="Button">
<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>
MainWindow.xaml file final code will look like below:
<Window x:Class="CurrencyConverter_Static.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_Static"
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>
Output:
Application core part
- The default code added in MainWindow.xaml.cs by Visual Studio 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_Static
{
/// <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_Static
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
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 dtCurrency = 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
dtCurrency.Columns.Add("Text");
//Add value column in DataTable
dtCurrency.Columns.Add("Value");
//Add rows in Datatable with text and value
dtCurrency.Rows.Add("--SELECT--", 0);
dtCurrency.Rows.Add("INR", 1);
dtCurrency.Rows.Add("USD", 75);
dtCurrency.Rows.Add("EUR", 85);
dtCurrency.Rows.Add("SAR", 20);
dtCurrency.Rows.Add("POUND", 5);
dtCurrency.Rows.Add("DEM", 43);
- In DataTable add two columns:
- Text
- Value
- Add some rows with data in data table:
//The data to currency Combobox is assigned from datatable
cmbFromCurrency.ItemsSource = dtCurrency.DefaultView;
//DisplayMemberPath Property is used to display data in Combobox
cmbFromCurrency.DisplayMemberPath = "Text";
//SelectedValuePath property is used to set the value in Combobox
cmbFromCurrency.SelectedValuePath = "Value";
//SelectedIndex property is used to bind hint in the Combobox. The default value is Select.
cmbFromCurrency.SelectedIndex = 0;
//All properties are set for 'To Currency' Combobox as 'From Currency' Combobox
cmbToCurrency.ItemsSource = dtCurrency.DefaultView;
cmbToCurrency.DisplayMemberPath = "Text";
cmbToCurrency.SelectedValuePath = "Value";
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 the DataTable column name.
- After adding the BindCurrency() method call it in MainWindow() method. Because when the application run MainWindow() method is called first.
Output:
//ClearControls used for clear all controls value
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 for Clearcontrols().
- This method is used to clear all control data which the user entered.
- Add the method in the MainWindow() method.
//Allow only the integer value 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() . The method is used for the Amount textbox only, which allows the use of numbers. I am using 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 the 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)
{
}
- Add the convert button click event. On clicking on the convert button this event fire.
//Create a variable as ConvertedValue with double data type to 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 it will show the below message box
MessageBox.Show("Please Enter Currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
//After clicking on message box OK sets the Focus on amount textbox
txtCurrency.Focus();
return;
}
//Else if the currency from is not selected or it is default text --SELECT--
else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0)
{
//It will show the message
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 Select Default Text --SELECT--
else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0)
{
//It will show the message
MessageBox.Show("Please Select Currency To", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
//Set focus on To Combobox
cmbToCurrency.Focus();
return;
}
- Declare a variable ConvertedValue with the double datatype. It’s 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 selected values are same
if(cmbFromCurrency.Text == cmbToCurrency.Text)
{
//The amount textbox value set in ConvertedValue.
//double.parse is used to convert 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 to place 000 after after the(.)
lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
else
{
//Calculation for currency converter is From Currency value multiply(*)
// with amount textbox value and then the total is divided(/) with To Currency value
ConvertedValue = (double.Parse(cmbFromCurrency.SelectedValue.ToString()) * double.Parse(txtCurrency.Text)) / double.Parse(cmbToCurrency.SelectedValue.ToString());
//Show in 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 To Currency is 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 ConvertedValue in the label.
//Clear button click event
private void Clear_Click(object sender, RoutedEventArgs e)
{
//ClearControls method is used to clear all control value
ClearControls();
}
- Create a clear button click event.
- Call the ClearControls() method to clear all controls from the input which the user entered.
MainWindow.xaml.cs final code
using System.Windows;
using System.Windows.Input;
//This library is used for Regular Expression
using System.Text.RegularExpressions;
//This library is used for DataTable
using System.Data;
namespace CurrencyConverter_Static
{
public partial class MainWindow: Window
{
public MainWindow()
{
InitializeComponent();
//ClearControls method is used to clear all control values
ClearControls();
//BindCurrency is used to bind currency name with the value in the Combobox
BindCurrency();
}
#region Bind Currency From and To Combobox
private void BindCurrency()
{
//Create a Datatable Object
DataTable dtCurrency = new DataTable();
//Add the text column in the DataTable
dtCurrency.Columns.Add("Text");
//Add the value column in the DataTable
dtCurrency.Columns.Add("Value");
//Add rows in the Datatable with text and value
dtCurrency.Rows.Add("--SELECT--", 0);
dtCurrency.Rows.Add("INR", 1);
dtCurrency.Rows.Add("USD", 75);
dtCurrency.Rows.Add("EUR", 85);
dtCurrency.Rows.Add("SAR", 20);
dtCurrency.Rows.Add("POUND", 5);
dtCurrency.Rows.Add("DEM", 43);
//Datatable data assigned from the currency combobox
cmbFromCurrency.ItemsSource = dtCurrency.DefaultView;
//DisplayMemberPath property is used to display data in the combobox
cmbFromCurrency.DisplayMemberPath = "Text";
//SelectedValuePath property is used to set the value in the combobox
cmbFromCurrency.SelectedValuePath = "Value";
//SelectedIndex property is used to bind the combobox to its default selected item
cmbFromCurrency.SelectedIndex = 0;
//All properties are set to To Currency combobox as it is in the From Currency combobox
cmbToCurrency.ItemsSource = dtCurrency.DefaultView;
cmbToCurrency.DisplayMemberPath = "Text";
cmbToCurrency.SelectedValuePath = "Value";
cmbToCurrency.SelectedIndex = 0;
}
#endregion
#region Button Click Event
//Convert the button click event
private void Convert_Click(object sender, RoutedEventArgs e)
{
//Create the variable as ConvertedValue with double datatype to store currency converted value
double ConvertedValue;
//Check if the amount textbox is Null or Blank
if (txtCurrency.Text == null || txtCurrency.Text.Trim() == "")
{
//If amount textbox is Null or Blank it will show this message box
MessageBox.Show("Please Enter Currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
//After clicking on messagebox OK set focus on amount textbox
txtCurrency.Focus();
return;
}
//Else if currency From is not selected or select default text --SELECT--
else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0)
{
//Show the message
MessageBox.Show("Please Select Currency From", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
//Set focus on the From Combobox
cmbFromCurrency.Focus();
return;
}
//Else if currency To is not selected or select default text --SELECT--
else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0)
{
//Show the message
MessageBox.Show("Please Select Currency To", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
//Set focus on the To Combobox
cmbToCurrency.Focus();
return;
}
//Check if From and To Combobox selected values are same
if(cmbFromCurrency.Text == cmbToCurrency.Text)
{
//Amount textbox value set in ConvertedValue.
//double.parse is used for converting the datatype String To Double.
//Textbox text have string and ConvertedValue is double Datatype
ConvertedValue = double.Parse(txtCurrency.Text);
//Show the label converted currency and converted currency name and ToString("N3") is used to place 000 after the dot(.)
lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
else
{
//Calculation for currency converter is From Currency value multiply(*)
//With the amount textbox value and then that total divided(/) with To Currency value
ConvertedValue = (double.Parse(cmbFromCurrency.SelectedValue.ToString()) * double.Parse(txtCurrency.Text)) / double.Parse(cmbToCurrency.SelectedValue.ToString());
//Show the label converted currency and converted currency name.
lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
}
//Clear Button click event
private void Clear_Click(object sender, RoutedEventArgs e)
{
//ClearControls method is used to clear all controls value
ClearControls();
}
#endregion
#region Extra Events
//ClearControls method is used to clear all controls value
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();
}
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) //Allow Only Integer in Text Box
{
//Regular Expression is used to add regex.
// Add Library using System.Text.RegularExpressions;
Regex regex = new Regex("^[0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
#endregion
}
}
Output:
Summary
- In this article, you have learned about the creation of the Currency Converter application in WPF. As of now, we used static data to assign currency value. In the upcoming, I will show you doing it using the database.